Class: Attributor::Model

Inherits:
Object
  • Object
show all
Includes:
Type
Defined in:
lib/attributor/types/model.rb

Direct Known Subclasses

FileUpload, Struct

Constant Summary collapse

MAX_EXAMPLE_DEPTH =
5
CIRCULAR_REFERENCE_MARKER =
'...'.freeze

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Type

included

Constructor Details

#initialize(data = nil) ⇒ Model

Returns a new instance of Model.



232
233
234
235
236
237
238
239
240
241
242
# File 'lib/attributor/types/model.rb', line 232

def initialize( data = nil)
  @lazy_attributes = ::Hash.new
  @validating = false
  @dumping = false
  if data
    loaded = self.class.load( data )
    @attributes = loaded.attributes
  else
    @attributes = ::Hash.new
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



288
289
290
291
292
293
294
295
296
297
298
# File 'lib/attributor/types/model.rb', line 288

def method_missing(name, *args)
  attribute_name = name.to_s
  attribute_name.chomp!('=')

  if self.class.attributes.has_key?(attribute_name.to_sym)
    self.class.define_accessors(attribute_name)
    return self.send(name, *args)
  end

  super
end

Class Attribute Details

.optionsObject (readonly)

Returns the value of attribute options.



21
22
23
# File 'lib/attributor/types/model.rb', line 21

def options
  @options
end

Instance Attribute Details

#dumpingObject (readonly)

Returns the value of attribute dumping.



229
230
231
# File 'lib/attributor/types/model.rb', line 229

def dumping
  @dumping
end

#lazy_attributesObject (readonly)

Returns the value of attribute lazy_attributes.



229
230
231
# File 'lib/attributor/types/model.rb', line 229

def lazy_attributes
  @lazy_attributes
end

#validatingObject (readonly)

Returns the value of attribute validating.



229
230
231
# File 'lib/attributor/types/model.rb', line 229

def validating
  @validating
end

Class Method Details

.attributes(opts = {}, &block) ⇒ Object

method to only define the block of attributes for the model This will be a lazy definition. So we’ll only save it in an instance class var for later.



190
191
192
193
194
195
196
197
198
199
# File 'lib/attributor/types/model.rb', line 190

def self.attributes(opts={},&block)
  if block_given?
    @saved_blocks.push(block)
    @options.merge!(opts)
  elsif @saved_blocks.any?
    self.definition
  end

  @attributes
end

.check_option!(name, value) ⇒ Object



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/attributor/types/model.rb', line 127

def self.check_option!(name, value)
  case name
  when :identity
    raise AttributorException, "Invalid identity type #{value.inspect}" unless value.kind_of?(::Symbol)
    :ok # FIXME ... actually do something smart, that doesn't break lazy attribute creation
  when :reference
    :ok # FIXME ... actually do something smart
  when :dsl_compiler
    :ok # FIXME ... actually do something smart
  when :dsl_compiler_options
    :ok
  else
    super
  end
end

.define_accessors(name) ⇒ Object

Define accessors for attribute of given name.

Parameters:

  • name (::Symbol)

    attribute name



29
30
31
32
33
# File 'lib/attributor/types/model.rb', line 29

def self.define_accessors(name)
  name = name.to_sym
  self.define_reader(name)
  self.define_writer(name)
end

.define_reader(name) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/attributor/types/model.rb', line 36

def self.define_reader(name)
  module_eval "    def \#{name}\n      return @attributes[:\#{name}] if @attributes.has_key?(:\#{name})\n\n      @attributes[:\#{name}] = begin\n        if (proc = @lazy_attributes.delete :\#{name})\n          if proc.arity > 0\n            proc.call(self)\n          else\n            proc.call\n          end\n        end\n      end\n    end\n  RUBY\nend\n", __FILE__, __LINE__ + 1

.define_writer(name) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/attributor/types/model.rb', line 55

def self.define_writer(name)
  attribute = self.attributes[name]
  context = ["assignment","of(#{name})"].freeze
  # note: paradoxically, using define_method ends up being faster for the writer
  #       attribute is captured by the block, saving us from having to retrieve it from
  #       the class's attributes hash on each write.
  module_eval do
    define_method(name.to_s + "=") do |value|
      # TODO: what type of context do we report with unscoped assignments?
      #  => for now this would report "assignment.of(field_name)" is that good?
      @attributes[name] = attribute.load(value,context)
    end
  end
end

.definitionObject

Returns the “compiled” definition for the model. By “compiled” I mean that it will create a new Compiler object with the saved options and saved block that has been passed in the ‘attributes’ method. This compiled object is memoized (remember, there’s one instance of a compiled definition PER MODEL CLASS). TODO: rework this with Model.finalize! support.



220
221
222
223
224
225
226
227
# File 'lib/attributor/types/model.rb', line 220

def self.definition
  blocks = @saved_blocks.shift(@saved_blocks.size)

  compiler = dsl_class.new(self, self.options)
  compiler.parse(*blocks)

  nil
end

.describe(shallow = false) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/attributor/types/model.rb', line 71

def self.describe(shallow=false)
  hash = super

  # Spit attributes if it's the root or if it's an anonymous structures
  if ( !shallow || self.name == nil) && self.attributes
    hash[:attributes] = self.attributes.each_with_object({}) do |(sub_name, sub_attribute), sub_attributes|
      sub_attributes[sub_name] = sub_attribute.describe(true)
    end
  end

  hash
end

.dsl_classObject



213
214
215
# File 'lib/attributor/types/model.rb', line 213

def self.dsl_class
  @options[:dsl_compiler] || DSLCompiler
end

.dump(value, **opts) ⇒ Object



119
120
121
# File 'lib/attributor/types/model.rb', line 119

def self.dump(value, **opts)
  value.dump(opts)
end

.example(context = nil, **values) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/attributor/types/model.rb', line 85

def self.example(context=nil, **values)
  result = self.new

  context = case context
  when nil
    ["#{self.name}-#{result.object_id.to_s}"]
  when ::String
    [context]
  else
    context
  end

  example_depth = context.size

  self.attributes.each do |sub_attribute_name,sub_attribute|
    if sub_attribute.attributes
       # TODO: add option to raise an exception in this case?
       next if example_depth > MAX_EXAMPLE_DEPTH
    end

    sub_context = self.generate_subcontext(context,sub_attribute_name)

    result.lazy_attributes[sub_attribute_name] = Proc.new do
      value = values.fetch(sub_attribute_name) do
        sub_attribute.example(sub_context, parent: result)
      end

      sub_attribute.load(value,sub_context)
    end
  end

  result
end

.from_hash(hash, context) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/attributor/types/model.rb', line 169

def self.from_hash(hash,context)
  model = self.new

  self.attributes.each do |attribute_name, attribute|
    # OPTIMIZE: deleting the keys as we go is mucho faster, but also very risky
    # Note: use "load" vs. attribute assignment so we can propagate the right context down.
    sub_context = self.generate_subcontext(context,attribute_name)
    model.attributes[attribute_name] = attribute.load(hash[attribute_name] || hash[attribute_name.to_s], sub_context)
  end

  unknown_keys = hash.keys.collect {|k| k.to_sym} - self.attributes.keys

  if unknown_keys.any?
    raise AttributorException, "Unknown attributes received: #{unknown_keys.inspect} while loading #{Attributor.humanize_context(context)}"
  end

  model
end

.inherited(klass) ⇒ Object



12
13
14
15
16
17
18
# File 'lib/attributor/types/model.rb', line 12

def self.inherited(klass)
  klass.instance_eval do
    @saved_blocks = []
    @options = {}
    @attributes = {}
  end
end

.load(value, context = Attributor::DEFAULT_ROOT_CONTEXT, **options) ⇒ Object

Model-specific decoding and coercion of the attribute.



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/attributor/types/model.rb', line 145

def self.load(value,context=Attributor::DEFAULT_ROOT_CONTEXT, **options)
  return value if value.nil?
  return value if value.kind_of?(self.native_type)

  context = Array(context)

  hash = case value
  when ::String
    # Strings are assumed to be JSON-serialized for now.
    begin
      JSON.parse(value)
    rescue
      raise DeserializationError, context: context, from: value.class, encoding: "JSON" , value: value
    end
  when ::Hash
    value
  else
    raise IncompatibleTypeError,  context: context, value_type: value.class, type: self
  end

  self.from_hash(hash,context)
end

.native_typeObject



123
124
125
# File 'lib/attributor/types/model.rb', line 123

def self.native_type
  self
end

.validate(object, context = Attributor::DEFAULT_ROOT_CONTEXT, _attribute) ⇒ Object



202
203
204
205
206
207
208
209
210
# File 'lib/attributor/types/model.rb', line 202

def self.validate(object,context=Attributor::DEFAULT_ROOT_CONTEXT,_attribute)
  context = [context] if context.is_a? ::String

  unless object.kind_of?(self)
    raise ArgumentError, "#{self.name} can not validate object of type #{object.class.name} for #{Attributor.humanize_context(context)}."
  end

  object.validate(context)
end

Instance Method Details

#attributesObject



270
271
272
273
274
275
# File 'lib/attributor/types/model.rb', line 270

def attributes
  @lazy_attributes.keys.each do |name|
    self.send(name)
  end
  @attributes
end

#dump(context: Attributor::DEFAULT_ROOT_CONTEXT, **opts) ⇒ Object



301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/attributor/types/model.rb', line 301

def dump(context: Attributor::DEFAULT_ROOT_CONTEXT, **opts)
  return CIRCULAR_REFERENCE_MARKER if @dumping

  @dumping = true

  self.attributes.each_with_object({}) do |(name, value), result|
    attribute = self.class.attributes[name]

    result[name.to_sym] = attribute.dump(value, context: context + [name] )
  end
ensure
  @dumping = false
end

#respond_to_missing?(name) ⇒ Boolean

Returns:



278
279
280
281
282
283
284
285
# File 'lib/attributor/types/model.rb', line 278

def respond_to_missing?(name,*)
  attribute_name = name.to_s
  attribute_name.chomp!('=')

  return true if self.class.attributes.key?(attribute_name.to_sym)

  super
end

#validate(context = Attributor::DEFAULT_ROOT_CONTEXT) ⇒ Object

TODO: memoize validation results here, but only after rejiggering how we store the context.

Two calls to validate() with different contexts should return get the same errors,
but with their respective contexts.


248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/attributor/types/model.rb', line 248

def validate(context=Attributor::DEFAULT_ROOT_CONTEXT)

  raise AttributorException, "validation conflict" if @validating
  @validating = true

  context = [context] if context.is_a? ::String

  self.class.attributes.each_with_object(Array.new) do |(sub_attribute_name, sub_attribute), errors|
    sub_context = self.class.generate_subcontext(context,sub_attribute_name)

    value = self.send(sub_attribute_name)
    if value.respond_to?(:validating) # really, it's a thing with sub-attributes
      next if value.validating
    end

    errors.push *sub_attribute.validate(value, sub_context)
  end
ensure
  @validating = false
end