Module: Cerializable::Model

Defined in:
lib/cerializable/model.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



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
# File 'lib/cerializable/model.rb', line 4

def self.included(base)
  base.extend ClassMethods

  base.class_eval do
    # #cerializable_hash delegates to the #run method of the model's 'cerializer' object.
    #
    # It accepts `:only`, `:except`, and `:methods` options which can be passed as a
    # symbol or as an array of symbols.
    #
    # Using the `:only` option will return a hash that only has the specified keys.
    #
    #     > comment.cerializable_hash(only: :id)
    #     => { id: 1 }
    #
    # Using the `:except` option will return a hash that has all default keys except those specified.
    #
    #     > comment.cerializable_hash(except: [:id, :user_id])
    #     => { body: '...sushi? ;)', deleted_at: nil }
    #
    # Using the `:methods` option add will add a key and value for each method specified.
    #
    # The key is the method name as a symbol.
    # The value is the return value given when calling the method on the model instance.
    #
    # The :methods option is processed after the :only and :except options.
    #
    #     > comment.cerializable_hash(only: id, methods: :hash])
    #     => { id: 1, hash: -2535926706119161824 }
    #
    def cerializable_hash(options = {})
      [:only, :except, :methods].each do |option_name|
        next if options[option_name].nil?

        unless options[option_name].is_a?(Symbol) || options[option_name].is_a?(Array)
          raise Exception, "'#{ option_name }' option must be of an Array or Symbol class."
        end
      end

      # serialize the instance using the class's cerializer object.
      hash = self.class.cerializer.run(self, options)

      # alter the hash according to the :only, :except, and :methods serialization options.
      ensure_is_array = proc { |arg| arg.class.ancestors.include?(Array) ? arg : Array.new(1, arg) }

      if except_options = options[:except] && ensure_is_array.call(options[:except])
        except_options.each { |key| hash.delete(key) }
      end

      if only_options = options[:only] && ensure_is_array.call(options[:only])
        hash.keys.each { |key| hash.delete(key) unless only_options.include?(key) }
      end

      if methods_options = options[:methods] && ensure_is_array.call(options[:methods])
        methods_options.each { |method_name| hash[method_name] = self.send(method_name) }
      end

      hash
    end
  end

end