Module: MediaartsScraper::Data::DataObject

Constant Summary collapse

NULL =
Object.new.freeze

Class Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



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
# File 'lib/mediaarts_scraper/data/data_object.rb', line 6

def self.included(klass)
  klass.class_eval do
    attr_reader :raw_data

    def initialize(raw_data)
      @raw_data = raw_data
      @attributes = Hash.new(NULL)
    end

    def attributes
      self.class.attributes
    end

    def attributes_without_copyrighted
      self.class.attributes_without_copyrighted
    end

    def self.attribute(method, en, copyrighted = false)
      attributes << method
      attributes_without_copyrighted << method unless copyrighted

      define_method(method) do
        if @attributes[method] == NULL
          if block_given?
            @attributes[method] = yield @raw_data[en]
          else
            @attributes[method] = @raw_data[en]
          end
        end

        @attributes[method]
      end
    end

    def self.attributes
      @_attributes_ = [] unless @_attributes_

      @_attributes_
    end

    def self.attributes_without_copyrighted
      @_attributes_without_copyrighted_ = [] unless @_attributes_without_copyrighted_

      @_attributes_without_copyrighted_
    end

    def to_json(*options)
      to_hash.to_json(*options)
    end

    def to_json_without_copyrighted(*options)
      to_hash_without_copyrighted.to_json(*options)
    end

    def to_hash
      to_hash0(attributes, :to_hash)
    end

    def to_hash_without_copyrighted
      to_hash0(attributes_without_copyrighted, :to_hash_without_copyrighted)
    end

    private

    def to_hash0(attributes, method)
      {}.tap { |hash|
        hash["class"] = self.class.name

        attributes.each do |attr|
          value = send(attr)

          hash[attr] = if value.is_a?(Array)
                         value.map { |item| item.respond_to?(method) ? item.send(method) : item }
                       elsif value.is_a?(Hash)
                         value.transform_values { |item| item.respond_to(method) ? item.send(method) : item }
                       elsif value.respond_to?(method)
                         value.send(method)
                       else
                         value
                       end
        end
      }
    end
  end
end