Module: HasMetadata::InstanceMethods
- Defined in:
- lib/has_metadata.rb
Overview
Instance methods that are added to your model.
Instance Method Summary collapse
- #as_json(options = {}) ⇒ Object
- #assign_multiparameter_attributes(pairs) ⇒ Object
- #inspect ⇒ Object
-
#metadata! ⇒ Metadata
An existing associated Metadata instance, or new, saved one if none was found.
- #to_xml(options = {}) ⇒ Object
Instance Method Details
#as_json(options = {}) ⇒ Object
109 110 111 112 113 114 |
# File 'lib/has_metadata.rb', line 109 def as_json(={}) ||= Hash.new # the JSON encoder can sometimes give us nil options? [:except] = Array.wrap([:except]) + [ :metadata_id ] [:methods] = Array.wrap([:methods]) + .keys - [:except].map(&:to_sym) super end |
#assign_multiparameter_attributes(pairs) ⇒ Object
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 |
# File 'lib/has_metadata.rb', line 123 def assign_multiparameter_attributes(pairs) fake_attributes = pairs.select { |(field, _)| self.class..include? field[0, field.index('(')].to_sym } fake_attributes.group_by { |(field, _)| field[0, field.index('(')] }.each do |field_name, parts| = self.class.[field_name.to_sym] if [:type] then args = parts.each_with_object([]) do |(part_name, value), ary| part_ann = part_name[part_name.index('(') + 1, part_name.length] index = part_ann.to_i - 1 raise "Out-of-bounds multiparameter argument index" unless index >= 0 ary[index] = if value.blank? then nil elsif part_ann.ends_with?('i)') then value.to_i elsif part_ann.ends_with?('f)') then value.to_f else value end end args.compact! send :"#{field_name}=", [:type].new(*args) unless args.empty? else raise "#{field_name} has no type and cannot be used for multiparameter assignment" end end super(pairs - fake_attributes) end |
#inspect ⇒ Object
164 165 166 |
# File 'lib/has_metadata.rb', line 164 def inspect "#<#{self.class.to_s} #{attributes.merge(.try(:data).try(:stringify_keys) || {}).map { |k,v| "#{k}: #{v.inspect}" }.join(', ')}>" end |
#metadata! ⇒ Metadata
Returns An existing associated Metadata instance, or new, saved one if none was found.
151 152 153 154 155 156 157 158 159 160 161 |
# File 'lib/has_metadata.rb', line 151 def if instance_variables.include?(:@metadata) && then else if new_record? then || else || Metadata.transaction { || } end end.set_fields self.class. end |
#to_xml(options = {}) ⇒ Object
116 117 118 119 120 |
# File 'lib/has_metadata.rb', line 116 def to_xml(={}) [:except] = Array.wrap([:except]) + [ :metadata_id ] [:methods] = Array.wrap([:methods]) + .keys - [:except].map(&:to_sym) super end |