Class: Bitmasker::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/bitmasker/generator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mask_name, model) ⇒ Generator

Returns a new instance of Generator.



3
4
5
6
7
8
9
10
11
12
13
14
# File 'lib/bitmasker/generator.rb', line 3

def initialize(mask_name, model)
  @bitmask_attributes = {}
  @bitmask_defaults = {}

  @model = model
  @mask_name = mask_name
  @field_name = mask_name.to_s + '_mask'

  @scope_name = mask_name.to_s + '_scope'

  @use_attr_accessible = false
end

Instance Attribute Details

#field_name=(value) ⇒ Object (writeonly) Also known as: field_name

Sets the attribute field_name

Parameters:

  • value

    the value to set the attribute field_name to.



23
24
25
# File 'lib/bitmasker/generator.rb', line 23

def field_name=(value)
  @field_name = value
end

#method_format=(value) ⇒ Object (writeonly) Also known as: method_format

Sets the attribute method_format

Parameters:

  • value

    the value to set the attribute method_format to.



17
18
19
# File 'lib/bitmasker/generator.rb', line 17

def method_format=(value)
  @method_format = value
end

Instance Method Details

#accessibleObject



32
33
34
# File 'lib/bitmasker/generator.rb', line 32

def accessible
  @use_attr_accessible = true
end

#attribute(name, mask, default = false) ⇒ Object



27
28
29
30
# File 'lib/bitmasker/generator.rb', line 27

def attribute(name, mask, default = false)
  @bitmask_attributes[name] = mask
  @bitmask_defaults[name] = default
end

#generateObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/bitmasker/generator.rb', line 36

def generate
  klass = BitmaskAttributes.make(@model, @field_name, @bitmask_attributes, @bitmask_defaults)
  scope_klass = BitmaskScope.make(@model, @field_name, @mask_name, @bitmask_attributes)

  @model.send :define_method, @mask_name do
    klass.new(self)
  end

  @model.singleton_class.send :define_method, @scope_name do
    scope_klass.new
  end

  @model.singleton_class.delegate "with_#{@mask_name}",
    "without_#{@mask_name}", "with_any_#{@mask_name}",
    to: @scope_name

  @bitmask_attributes.each do |attribute, mask|
    @model.delegate attribute, "#{attribute}?", "#{attribute}=", "#{attribute}_was",
      to: @mask_name

    @model.attr_accessible attribute if @use_attr_accessible
  end
end