lib/tmdb_party/attributes.rb in tmdb_party-0.4.1 vs lib/tmdb_party/attributes.rb in tmdb_party-0.5.0
- old
+ new
@@ -18,19 +18,18 @@
attribute name, options unless name.blank?
end
end
def attribute(name, options)
- options.replace({:type => 'nil', :lazy=>false}.merge(options))
- raise "Name can't be empty" if name.blank?
- lazy_load = "self.#{options[:lazy]} unless self.loaded?" if options[:lazy]
- class_eval <<-EOS
- def #{name}
- #{lazy_load}
- @#{name} ||= decode_raw_attribute(@attributes['#{name}'], #{options[:type]}) if @attributes
- end
- EOS
+ options = {:type => 'nil', :lazy => false}.merge(options)
+ raise ArgumentError, "Name can't be empty" if name.blank?
+
+ class_eval <<-EVAL
+ def #{name}
+ read_or_load_attribute('#{name}', #{options[:type]}, #{options[:lazy].inspect})
+ end
+ EVAL
end
end
module InstanceMethods
@@ -41,12 +40,29 @@
def loaded?
@loaded
end
private
- def decode_raw_attribute(value, type)
- return nil unless value
- type.respond_to?(:parse) ? type.parse(value) : value
- end
+ def read_or_load_attribute(name, type, lazy_method)
+ if lazy_method.is_a?(Symbol) and raw_attribute_missing?(name) and not loaded?
+ self.send(lazy_method)
+ end
+ read_attribute(name, type)
+ end
+
+ def read_attribute(name, type = nil)
+ @attributes_cache ||= {}
+ @attributes_cache[name] ||= decode_raw_attribute(@attributes[name], type) if @attributes
+ end
+
+ def raw_attribute_missing?(name)
+ not @attributes.has_key?(name.to_s)
+ end
+
+ def decode_raw_attribute(value, type)
+ return nil unless value
+ type.respond_to?(:parse) ? type.parse(value) : value
+ end
+
end
end
end
\ No newline at end of file