lib/supermodel/base.rb in supermodel-0.0.2 vs lib/supermodel/base.rb in supermodel-0.0.4

- old
+ new

@@ -3,10 +3,18 @@ include ActiveModel::Dirty class << self attr_accessor_with_default(:primary_key, 'id') #:nodoc: + def attributes(*attributes) + @known_attributes = attributes.map(&:to_s) + end + + def known_attributes + @known_attributes ||= [] + end + def records @records ||= [] end def raw_find(id) #:nodoc: @@ -24,11 +32,11 @@ item = records[0] item && item.dup end def last - item = records[1] + item = records[-1] item && item.dup end def count records.length @@ -64,25 +72,31 @@ def create(atts = {}) rec = self.new(atts) rec.save && rec end - def method_missing(method_symbol, *arguments) #:nodoc: + def method_missing(method_symbol, *args) #:nodoc: method_name = method_symbol.to_s if method_name =~ /^find_by_(\w+)!/ - send("find_by_#{$1}", *arguments) || raise(UnknownRecord) + send("find_by_#{$1}", *args) || raise(UnknownRecord) elsif method_name =~ /^find_by_(\w+)/ - records.find {|r| r.send($1) == arguments.first } + records.find {|r| r.send($1) == args.first } + elsif method_name =~ /^find_or_create_by_(\w+)/ + send("find_by_#{$1}", *args) || create($1 => args.first) else super end end end attr_accessor :attributes + def known_attributes + self.class.known_attributes + self.attributes.keys.map(&:to_s) + end + def initialize(attributes = {}) @attributes = {}.with_indifferent_access load(attributes) end @@ -162,10 +176,12 @@ def respond_to?(method, include_priv = false) method_name = method.to_s if attributes.nil? super + elsif known_attributes.include?(method_name) + true elsif method_name =~ /(?:=|\?)$/ && attributes.include?($`) true else super end @@ -219,16 +235,19 @@ when "?" attributes[$`] end else return attributes[method_name] if attributes.include?(method_name) + return nil if known_attributes.include?(method_name) super end end end class Base extend ActiveModel::Naming include ActiveModel::Conversion + include ActiveModel::Serializers::JSON + include ActiveModel::Serializers::Xml include Observing, Validations, Callbacks end end \ No newline at end of file