Class: Dupe::Model::Schema::AttributeTemplate

Inherits:
Object
  • Object
show all
Defined in:
lib/superdupe/attribute_template.rb

Overview

This class represents an attribute template. An attribute template consists of an attribute name (a symbol), a potential default value (nil if not specified), and a potential transformer proc.

Defined Under Namespace

Classes: NilValue

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}) ⇒ AttributeTemplate

Returns a new instance of AttributeTemplate.



16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/superdupe/attribute_template.rb', line 16

def initialize(name, options={})
  default = options[:default]
  transformer = options[:transformer]
  
  if transformer
    raise ArgumentError, "Your transformer must be a kind of proc." if !transformer.kind_of?(Proc)
    raise ArgumentError, "Your transformer must accept a parameter." if transformer.arity != 1
  end
  
  @name = name
  @default = default
  @transformer = transformer
end

Instance Attribute Details

#defaultObject (readonly)

Returns the value of attribute default.



14
15
16
# File 'lib/superdupe/attribute_template.rb', line 14

def default
  @default
end

#nameObject (readonly)

Returns the value of attribute name.



12
13
14
# File 'lib/superdupe/attribute_template.rb', line 12

def name
  @name
end

#transformerObject (readonly)

Returns the value of attribute transformer.



13
14
15
# File 'lib/superdupe/attribute_template.rb', line 13

def transformer
  @transformer
end

Instance Method Details

#generate(value = NilValue) ⇒ Object

Suppose we have the following attribute template:

console> a = Dupe::Model::Schema::AttributeTemplate.new(:title)

If we call generate with no parameter, we’ll get back the following:

console> a.generate
  ===> :title, nil

If we call generate with a parameter, we’ll get back the following:

console> a.generate 'my value'
  ===> :title, 'my value'

If we setup an attribute template with a transformer:

console> a = 
          Dupe::Model::Schema::AttributeTemplate.new(
            :title, 
            :default => 'default value', 
            :transformer => proc {|dont_care| 'test'}
          )

Then we’ll get back the following when we call generate:

console> a.generate
  ===> :title, 'default value'

console> a.generate 'my value'
  ===> :title, 'test'


59
60
61
62
63
64
65
66
67
# File 'lib/superdupe/attribute_template.rb', line 59

def generate(value=NilValue)
  if value == NilValue
    v = @default.respond_to?(:call) ? @default.call : (@default.dup rescue @default)
  else
    v = (@transformer ? @transformer.call(value) : value)
  end
  
  return @name, v
end