Module: Her::Model::Attributes

Extended by:
ActiveSupport::Concern
Included in:
Her::Model
Defined in:
lib/her/model/attributes.rb

Overview

This module handles all methods related to model attributes

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &blk) ⇒ Object

Handles missing methods



73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/her/model/attributes.rb', line 73

def method_missing(method, *args, &blk)
  if method.to_s =~ /[?=]$/ || @attributes.include?(method)
    # Extract the attribute
    attribute = method.to_s.sub(/[?=]$/, '')

    # Create a new `attribute` methods set
    self.class.attributes(*attribute)

    # Resend the method!
    send(method, *args, &blk)
  else
    super
  end
end

Instance Method Details

#assign_attributes(new_attributes) ⇒ Object Also known as: attributes=

Assign new attributes to a resource

Examples:

class User
  include Her::Model
end

user = User.find(1) # => #<User id=1 name="Tobias">
user.assign_attributes(name: "Lindsay")
user.changes # => { :name => ["Tobias", "Lindsay"] }


103
104
105
106
107
108
109
110
111
112
113
# File 'lib/her/model/attributes.rb', line 103

def assign_attributes(new_attributes)
  @attributes ||= attributes
  # Use setter methods first
  unset_attributes = Her::Model::Attributes.use_setter_methods(self, new_attributes)

  # Then translate attributes of associations into association instances
  parsed_attributes = self.class.parse_associations(unset_attributes)

  # Then merge the parsed_data into @attributes.
  @attributes.merge!(parsed_attributes)
end

#attributesObject



116
117
118
# File 'lib/her/model/attributes.rb', line 116

def attributes
  @attributes ||= HashWithIndifferentAccess.new
end

#idObject

Return the value of the model ‘primary_key` attribute



136
137
138
# File 'lib/her/model/attributes.rb', line 136

def id
  @attributes[self.class.primary_key]
end

#initialize(attributes = {}) ⇒ Object

Initialize a new object with data

User.new(name: "Tobias") # => #<User name="Tobias">

Examples:

class User
  include Her::Model
end

Parameters:

  • attributes (Hash) (defaults to: {})

    The attributes to initialize the object with

Options Hash (attributes):

  • :_metadata (Hash, Array)
  • :_errors (Hash, Array)
  • :_destroyed (Boolean)


20
21
22
23
24
25
26
27
28
29
# File 'lib/her/model/attributes.rb', line 20

def initialize(attributes={})
  attributes ||= {}
  @metadata = attributes.delete(:_metadata) || {}
  @response_errors = attributes.delete(:_errors) || {}
  @destroyed = attributes.delete(:_destroyed) || false

  attributes = self.class.default_scope.apply_to(attributes)
  assign_attributes(attributes)
  run_callbacks :initialize
end