Module: ApiResource::Attributes::ClassMethods

Defined in:
lib/api_resource/attributes.rb

Instance Method Summary collapse

Instance Method Details

#attribute?(name) ⇒ Boolean

Returns:

  • (Boolean)


107
108
109
# File 'lib/api_resource/attributes.rb', line 107

def attribute?(name)
  self.attribute_names.include?(name.to_sym)
end

#clear_attributes ⇒ Object



115
116
117
118
119
# File 'lib/api_resource/attributes.rb', line 115

def clear_attributes
  self.attribute_names.clear
  self.public_attribute_names.clear
  self.protected_attribute_names.clear
end

#define_accessor_methods(meth) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/api_resource/attributes.rb', line 80

def define_accessor_methods(meth)
  # Override the setter for dirty tracking
  self.class_eval <<-EOE, __FILE__, __LINE__ + 1
    def #{meth}
      read_attribute(:#{meth})
    end
  
    def #{meth}=(new_val)
      write_attribute(:#{meth}, new_val)
    end
    
    def #{meth}?
      read_attribute(:#{meth}).present?
    end
  EOE
  # sets up dirty tracking
  define_attribute_method(meth)
end

#define_attribute_type(field, type) ⇒ Object



99
100
101
102
103
104
# File 'lib/api_resource/attributes.rb', line 99

def define_attribute_type(field, type)
  unless self.typecasters.keys.include?(type.to_sym)
    raise "#{type} is not a valid type" 
  end
  self.attribute_types = self.attribute_types.merge(field => type.to_sym)
end

#define_attributes(*args) ⇒ Object



64
65
66
67
68
69
70
# File 'lib/api_resource/attributes.rb', line 64

def define_attributes(*args)
  args.each do |arg|
    self.store_attribute_data(arg, :public)
  end
  self.attribute_names.uniq!
  self.public_attribute_names.uniq!
end

#define_protected_attributes(*args) ⇒ Object



72
73
74
75
76
77
78
# File 'lib/api_resource/attributes.rb', line 72

def define_protected_attributes(*args)
  args.each do |arg|
    self.store_attribute_data(arg, :protected)
  end
  self.attribute_names.uniq!
  self.protected_attribute_names.uniq!
end

#protected_attribute?(name) ⇒ Boolean

Returns:

  • (Boolean)


111
112
113
# File 'lib/api_resource/attributes.rb', line 111

def protected_attribute?(name)
  self.protected_attribute_names.include?(name.to_sym)
end

#store_attribute_data(arg, type) ⇒ Object

stores the attribute type data and the name of the attributes we are creating



123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/api_resource/attributes.rb', line 123

def store_attribute_data(arg, type)
  if arg.is_a?(Array)
    self.define_attribute_type(arg.first, arg.second)
    arg = arg.first
  end
  self.attribute_names += [arg.to_sym]
  self.send(
    "#{type}_attribute_names=",
    self.send("#{type}_attribute_names") + [arg.to_sym]
  )
  self.define_accessor_methods(arg)
end