Class: Userbin::Model

Inherits:
Object
  • Object
show all
Includes:
Her::Model
Defined in:
lib/userbin/models/model.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ Model

Returns a new instance of Model


15
16
17
18
19
# File 'lib/userbin/models/model.rb', line 15

def initialize(args = {})
  # allow initializing with id as a string
  args = { id: args } if args.is_a? String
  super(args)
end

Class Method Details

.instance_custom(method, action) ⇒ Object


48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/userbin/models/model.rb', line 48

def self.instance_custom(method, action)
  #
  # Add method calls to association: user.challenges.verify(id, attributes)
  #
  AssociationProxy.class_eval <<-RUBY, __FILE__, __LINE__ + 1
    install_proxy_methods :association, :#{action}
  RUBY
  HasManyAssociation.class_eval <<-RUBY, __FILE__, __LINE__ + 1
    def #{action}(id, attributes={})
      @klass.build({:id => id, :"\#{@parent.singularized_resource_name}_id" => @parent.id}).#{action}(attributes)
    end
  RUBY

  #
  # Add method call to instance: user.enable_mfa
  #
  class_eval <<-RUBY, __FILE__, __LINE__ + 1
    def #{action}(params={})
      self.class.#{method}("\#{request_path}/#{action.to_s.delete('!')}", params)
    end
  RUBY
end

Instance Method Details

#attributesObject

Transform model.user.id to model.user_id to allow calls on nested models


22
23
24
25
26
27
28
29
# File 'lib/userbin/models/model.rb', line 22

def attributes
  attrs = super
  if attrs['user'] && attrs['user']['id']
    attrs.merge!('user_id' => attrs['user']['id'])
    attrs.delete 'user'
  end
  attrs
end

#to_jsonObject

Remove the auto-generated embedded User model to prevent recursion


32
33
34
35
36
37
38
# File 'lib/userbin/models/model.rb', line 32

def to_json
  attrs = attributes
  if attrs['user'] && attrs['user']['id'] == '$current'
    attrs.delete 'user'
  end
  attrs.to_json
end