Skip to content

Commit

Permalink
Restore use of ActiveModel::Model
Browse files Browse the repository at this point in the history
  • Loading branch information
bf4 committed Nov 21, 2016
1 parent ff1f1e8 commit be534ef
Showing 1 changed file with 8 additions and 50 deletions.
58 changes: 8 additions & 50 deletions lib/active_model_serializers/model.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@
module ActiveModelSerializers
class Model
include ActiveModel::Serializers::JSON
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
extend ActiveModel::Translation
include ActiveModel::Model

class_attribute :attribute_names
self.attribute_names = []
Expand All @@ -20,6 +17,13 @@ def self.attributes(*names)
attributes :id
attr_writer :updated_at

attr_reader :errors

def initialize(attributes = {})
@errors = ActiveModel::Errors.new(self)
super
end

# Defaults to the downcased model name.
def id
@id ||= self.class.name.downcase
Expand All @@ -35,14 +39,6 @@ def updated_at
defined?(@updated_at) ? @updated_at : File.mtime(__FILE__)
end

attr_reader :errors

def initialize(attributes = {})
assign_attributes(attributes) if attributes
@errors = ActiveModel::Errors.new(self)
super()
end

def attributes
attribute_names.each_with_object({}) do |attribute_name, result|
result[attribute_name] = public_send(attribute_name)
Expand All @@ -59,43 +55,5 @@ def self.lookup_ancestors
[self]
end
# :nocov:

def assign_attributes(new_attributes)
unless new_attributes.respond_to?(:stringify_keys)
fail ArgumentError, 'When assigning attributes, you must pass a hash as an argument.'
end
return if new_attributes.blank?

attributes = new_attributes.stringify_keys
_assign_attributes(attributes)
end

private

def _assign_attributes(attributes)
attributes.each do |k, v|
_assign_attribute(k, v)
end
end

def _assign_attribute(k, v)
fail UnknownAttributeError.new(self, k) unless respond_to?("#{k}=")
public_send("#{k}=", v)
end

def persisted?
false
end

# Raised when unknown attributes are supplied via mass assignment.
class UnknownAttributeError < NoMethodError
attr_reader :record, :attribute

def initialize(record, attribute)
@record = record
@attribute = attribute
super("unknown attribute '#{attribute}' for #{@record.class}.")
end
end
end
end

0 comments on commit be534ef

Please sign in to comment.