Class: Opera::Operation::AttributesDSL

Inherits:
Object
  • Object
show all
Defined in:
lib/opera/operation/attributes_dsl.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass:, block_name:, allowed: [:attr_reader]) ⇒ AttributesDSL

Returns a new instance of AttributesDSL.



8
9
10
11
12
# File 'lib/opera/operation/attributes_dsl.rb', line 8

def initialize(klass:, block_name:, allowed: [:attr_reader])
  @klass = klass
  @allowed = allowed
  @block_name = block_name
end

Instance Attribute Details

#allowedObject

Returns the value of attribute allowed.



6
7
8
# File 'lib/opera/operation/attributes_dsl.rb', line 6

def allowed
  @allowed
end

#block_nameObject

Returns the value of attribute block_name.



6
7
8
# File 'lib/opera/operation/attributes_dsl.rb', line 6

def block_name
  @block_name
end

#klassObject

Returns the value of attribute klass.



6
7
8
# File 'lib/opera/operation/attributes_dsl.rb', line 6

def klass
  @klass
end

Instance Method Details

#attr_accessor(*attributes, **options) ⇒ Object

Raises:

  • (NoMethodError)


49
50
51
52
53
54
# File 'lib/opera/operation/attributes_dsl.rb', line 49

def attr_accessor(*attributes, **options)
  raise NoMethodError, "You cannot use attr_accessor inside #{klass.name}##{block_name}" unless allowed.include?(:attr_accessor)

  attr_reader(*attributes, **options)
  attr_writer(*attributes)
end

#attr_reader(*attributes, **options) ⇒ Object

Raises:

  • (NoMethodError)


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/opera/operation/attributes_dsl.rb', line 14

def attr_reader(*attributes, **options)
  raise NoMethodError, "You cannot use attr_reader inside #{klass.name}##{block_name}" unless allowed.include?(:attr_reader)

  attributes.each do |attribute|
    klass.check_method_availability!(attribute)

    method = block_name
    klass.define_method(attribute) do
      value = if send(method).key?(attribute)
        send(method)[attribute]
      elsif options[:default]
        instance_exec(&options[:default])
      end

      if send(method).frozen?
        send(method)[attribute] || value
      else
        send(method)[attribute] ||= value
      end
    end
  end
end

#attr_writer(*attributes, **options) ⇒ Object

Raises:

  • (NoMethodError)


37
38
39
40
41
42
43
44
45
46
47
# File 'lib/opera/operation/attributes_dsl.rb', line 37

def attr_writer(*attributes, **options)
  raise NoMethodError, "You cannot use attr_writer inside #{klass.name}##{block_name}" unless allowed.include?(:attr_accessor)

  attributes.each do |attribute|
    klass.check_method_availability!("#{attribute}=")
    method = block_name
    klass.define_method("#{attribute}=") do |value|
      send(method)[attribute] = value
    end
  end
end