File: varia_model.rb

package info (click to toggle)
ruby-varia-model 0.6.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 204 kB
  • sloc: ruby: 783; makefile: 4
file content (303 lines) | stat: -rw-r--r-- 7,537 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
require 'buff/extensions'
require 'json'

module VariaModel
  require_relative 'varia_model/version'
  require_relative 'varia_model/attributes'

  module ClassMethods
    ASSIGNMENT_MODES = [
      :whitelist,
      :carefree
    ]

    # @return [VariaModel::Attributes]
    def attributes
      @attributes ||= Attributes.new
    end

    # @return [Hashie::Mash]
    def validations
      @validations ||= Hashie::Mash.new
    end

    # @return [Symbol]
    def assignment_mode
      @assignment_mode ||= :whitelist
    end

    # Set the attribute mass assignment mode
    #   * :whitelist - only attributes defined on the class will have values set
    #   * :carefree  - values will be set for attributes that are not explicitly defined
    #                  in the class definition
    #
    # @param [Symbol] mode
    #   an assignment mode to use @see {ASSIGNMENT_MODES}
    def set_assignment_mode(mode)
      unless ASSIGNMENT_MODES.include?(mode)
        raise ArgumentError, "unknown assignment mode: #{mode}"
      end

      @assignment_mode = mode
    end

    # @param [#to_s] name
    # @option options [Symbol, Array<Symbol>] :type
    # @option options [Buff::Boolean] :required
    # @option options [Object] :default
    # @option options [Proc] :coerce
    def attribute(name, options = {})
      name = name.to_s
      options[:type] = Array(options[:type])
      options[:required] ||= false

      register_attribute(name, options)
      define_mimic_methods(name, options)
    end

    # @param [String] name
    #
    # @return [Array]
    def validations_for(name)
      self.validations[name] ||= Array.new
    end

    # @param [Constant, Array<Constant>] types
    # @param [VariaModel] model
    # @param [String] key
    #
    # @return [Array]
    def validate_kind_of(types, model, key)
      errors  = Array.new
      types   = types.uniq
      matches = false

      types.each do |type|
        if model.get_attribute(key).is_a?(type)
          matches = true
          break
        end
      end

      if matches
        [ :ok, "" ]
      else
        types_msg = types.collect { |type| "'#{type}'" }
        [ :error, "Expected attribute: '#{key}' to be a type of: #{types_msg.join(', ')}" ]
      end
    end

    # Validate that the attribute on the given model has a non-nil value assigned
    #
    # @param [VariaModel] model
    # @param [String] key
    #
    # @return [Array]
    def validate_required(model, key)
      if model.get_attribute(key).nil?
        [ :error, "A value is required for attribute: '#{key}'" ]
      else
        [ :ok, "" ]
      end
    end

    private

      def register_attribute(name, options = {})
        if options[:type] && options[:type].any?
          unless options[:required]
            options[:type] << NilClass
          end
          register_validation(name, lambda { |object, key| validate_kind_of(options[:type], object, key) })
        end

        if options[:required]
          register_validation(name, lambda { |object, key| validate_required(object, key) })
        end

        class_eval do
          new_attributes = Attributes.from_dotted_path(name, options[:default])
          self.attributes.merge!(new_attributes)

          if options[:coerce].is_a?(Proc)
            register_coercion(name, options[:coerce])
          end
        end
      end

      def register_validation(name, fun)
        self.validations[name] = (self.validations_for(name) << fun)
      end

      def register_coercion(name, fun)
        self.attributes.container(name).set_coercion(name.split('.').last, fun)
      end

      def define_mimic_methods(name, options = {})
        fun_name = name.split('.').first

        class_eval do
          define_method(fun_name) do
            _attributes_[fun_name]
          end

          define_method("#{fun_name}=") do |value|
            value = if options[:coerce].is_a?(Proc)
              options[:coerce].call(value)
            else
              value
            end

            _attributes_[fun_name] = value
          end
        end
      end
  end

  class << self
    def included(base)
      base.extend(ClassMethods)
    end
  end

  # @return [Hashie::Mash]
  def validate
    self.class.validations.each do |attr_path, validations|
      validations.each do |validation|
        status, messages = validation.call(self, attr_path)

        if status == :error
          if messages.is_a?(Array)
            messages.each do |message|
              self.add_error(attr_path, message)
            end
          else
            self.add_error(attr_path, messages)
          end
        end
      end
    end

    self.errors
  end

  # @return [Buff::Boolean]
  def valid?
    validate.empty?
  end

  # @return [Hashie::Mash]
  def errors
    @errors ||= Hashie::Mash.new
  end

  # Assigns the attributes of a model from a given hash of attributes.
  #
  # If the assignment mode is set to `:whitelist`, then only the values of keys which have a
  # corresponding attribute definition on the model will be set. All other keys will have their
  # values ignored.
  #
  # If the assignment mode is set to `:carefree`, then the attributes hash will be populated
  # with any key/values that are provided.
  #
  # @param [Hash] new_attrs
  def mass_assign(new_attrs = {})
    case self.class.assignment_mode
    when :whitelist
      whitelist_assign(new_attrs)
    when :carefree
      carefree_assign(new_attrs)
    end
  end

  # @param [#to_s] key
  #
  # @return [Object]
  def get_attribute(key)
    eval_as_proc(_attributes_.berks_dig(key.to_s))
  end
  alias_method :[], :get_attribute

  # @param [#to_s] key
  # @param [Object] value
  def set_attribute(key, value)
    _attributes_.deep_merge!(Attributes.from_dotted_path(key.to_s, value))
  end
  alias_method :[]=, :set_attribute

  # @param [#to_hash] hash
  #
  # @return [self]
  def from_hash(hash)
    mass_assign(hash.to_hash)
    self
  end

  # @param [String] data
  #
  # @return [self]
  def from_json(data)
    mass_assign(JSON.parse(data))
    self
  end

  # The storage hash containing all of the key/values for this object's attributes
  #
  # @return [Hashie::Mash]
  def _attributes_
    @_attributes_ ||= self.class.attributes.dup
  end
  alias_method :to_hash, :_attributes_

  # @option options [Buff::Boolean] :symbolize_keys
  # @option options [Class, Symbol, String] :adapter
  #
  # @return [String]
  def to_json(*options)
    as_json.to_json(*options)
  end

  # @return [Hash]
  def as_json(*)
    opts = {}
    opts[JSON.create_id] = self.class.name if JSON.create_id
    to_hash.merge(opts)
  end

  # Convert the object to a hash.
  def to_hash
    _attributes_.inject({}) { |h, (k,v)| h[k] = eval_as_proc(v); h }
  end

  protected

    # @param [String] attribute
    # @param [String] message
    def add_error(attribute, message)
      self.errors[attribute] ||= Array.new
      self.errors[attribute] << message
    end

  private

    # Send #call to the given object if it responds to it. If it doesn't, just return the
    # object.
    #
    # @param [#call]
    def eval_as_proc(obj)
      obj.respond_to?(:call) ? obj.call : obj
    end

    def carefree_assign(new_attrs = {})
      _attributes_.deep_merge!(new_attrs)
    end

    def whitelist_assign(new_attrs = {})
      self.class.attributes.dotted_paths.each do |dotted_path|
        value = new_attrs.berks_dig(dotted_path)
        next if value.nil?

        set_attribute(dotted_path, value)
      end
    end
end