Class: McRecord::Base

Inherits:
Object
  • Object
show all
Extended by:
ActiveSupport::Concern
Defined in:
lib/mc_record/base.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes) ⇒ Base

Returns a new instance of Base.

Parameters:

  • (OpenStruct)


13
14
15
# File 'lib/mc_record/base.rb', line 13

def initialize(attributes)
  @attributes = attributes
end

Class Method Details

.allObject

return Array<OpenStruct>



24
25
26
27
28
29
30
31
# File 'lib/mc_record/base.rb', line 24

def self.all
  contents = fetch_contents
  contents.flatten!

  open_structs_to_instances(contents)
rescue MicroCMS::APIError
  raise ContentNotFound
end

.config(service_domain:, api_key:, end_point:) ⇒ Object



17
18
19
20
21
# File 'lib/mc_record/base.rb', line 17

def self.config(service_domain:, api_key:, end_point:)
  MicroCMS.service_domain = service_domain
  MicroCMS.api_key = api_key
  @@end_point = end_point
end

.find(id) ⇒ Object

Parameters:

  • (String)


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/mc_record/base.rb', line 34

def self.find(id)
  raise "wrong type of argument(expected String)" unless id.instance_of?(String)

  # OpenStruct
  api_result = MicroCMS.get(
                @@end_point,
                id
              )

  attr_names = api_result.to_h.keys
  attr_names.each do |attr_name|
    define_method_attribute_if_needed(attr_name)
  end

  self.new(api_result)
rescue MicroCMS::APIError
  raise ContentNotFound
end

.where(arg) ⇒ Object

Parameters:

  • (Hash)

Raises:

  • (ArgumentError)


54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/mc_record/base.rb', line 54

def self.where(arg)
  raise ArgumentError, "wrong type of argument(expected Hash)" unless arg.instance_of?(Hash)

  param = build_filter_params(arg)

  raise "param not specified" if param == ""

  contents = fetch_contents(param)
  contents.flatten!

  open_structs_to_instances(contents)
end

.where_not(arg) ⇒ Object

Parameters:

  • (Hash)

Raises:

  • (ArgumentError)


68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/mc_record/base.rb', line 68

def self.where_not(arg)
  raise ArgumentError, "wrong type of argument(expected Hash)" unless arg.instance_of?(Hash)

  param = build_not_filter_params(arg)

  raise "param not specified" if param == ""

  contents = fetch_contents(param)
  contents.flatten!

  open_structs_to_instances(contents)
end