Module: ActiveRecordJsonMap

Defined in:
lib/active_record_json_map.rb,
lib/active_record_json_map/version.rb

Constant Summary collapse

VERSION =
"0.1.0"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ 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
# File 'lib/active_record_json_map.rb', line 4

def self.included klass
  klass.class_variable_set("@@format", klass.to_s.underscore)

  if klass.ancestors.include? ActiveRecord::Base
    const_get("#{klass.to_s}::ActiveRecord_Relation").class_eval do
      def json_map key=nil, *args, **hash
        self.map {|it| it.json key, *args, **hash}
      rescue ArgumentError
        self.map {|it| it.json key}
      end
    end

    const_get("#{klass.to_s}::ActiveRecord_AssociationRelation").class_eval do
      def json_map key=nil, *args, **hash
        self.map {|it| it.json key, *args, **hash}
      rescue ArgumentError
        self.map {|it| it.json key}
      end
    end

    const_get("#{klass.to_s}::ActiveRecord_Associations_CollectionProxy").class_eval do
      def json_map key=nil, *args, **hash
        self.map {|it| it.json key, *args, **hash}
      rescue ArgumentError
        self.map {|it| it.json key}
      end
    end
  end
end

Instance Method Details

#format!(hash = {}, key: nil, **other) ⇒ Object



38
39
40
41
42
# File 'lib/active_record_json_map.rb', line 38

def format! hash={}, key: nil, **other
  hash.merge! other
  hash[:format] ||= key ? "#{self.class.to_s.underscore}_#{key}" : nil || @format || self.class.class_variable_get("@@format")
  return hash
end

#json(key = nil, *args, **hash) ⇒ Object



34
35
36
# File 'lib/active_record_json_map.rb', line 34

def json key=nil, *args, **hash
  format!((key ? self.send(key, *args, **hash) : self.attributes), key: key)
end