Module: Statinize::DSL

Included in:
Statinizer
Defined in:
lib/statinize/dsl.rb

Instance Method Summary collapse

Instance Method Details

#attribute(*attrs, **options) ⇒ Object



4
5
6
7
8
# File 'lib/statinize/dsl.rb', line 4

def attribute(*attrs, **options)
  attrs.each do |attr|
    Attribute.create(klass, attr, options) unless attribute? attr
  end
end

#before(&block) ⇒ Object



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

def before(&block)
  return unless block_given?

  before_callbacks << block
end

#force(force = nil) ⇒ Object



44
45
46
# File 'lib/statinize/dsl.rb', line 44

def force(force = nil)
  force.nil? ? @force : @force = force
end

#validate(*attrs, **options) ⇒ Object



10
11
12
13
14
15
16
# File 'lib/statinize/dsl.rb', line 10

def validate(*attrs, **options)
  attrs.each do |attr|
    attribute = attributes.find { _1.name == attr }
    attribute = Attribute.create(klass, attr) unless attribute
    attribute.add_options(options)
  end
end

#with(**options, &block) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/statinize/dsl.rb', line 18

def with(**options, &block)
  # create new statinizer instance
  instance = self.class.new(klass)
  instance.force(force)

  # execute block in the context of that statinizer
  # while it's attached to the klass
  # then rewind and attach the original statinizer(self)
  # back to the klass
  klass.instance_variable_set(:@statinizer, instance)
  instance.instance_exec(&block)
  klass.instance_variable_set(:@statinizer, self)

  # merge the newly created statinizer with the options
  instance.merge_options(**options)

  # populate self with the instance's attributes
  populate(instance.attributes)
end