Module: Erector::Needs::ClassMethods

Defined in:
lib/erector/needs.rb

Instance Method Summary collapse

Instance Method Details

#get_needsObject



59
60
61
# File 'lib/erector/needs.rb', line 59

def get_needs
  @needs || []
end

#inherited(subclass) ⇒ Object

Class method by which widget classes can declare that they need certain parameters. If needed parameters are not passed in to #new, then an exception will be thrown (with a hopefully useful message about which parameters are missing). This is intended to catch silly bugs like passing in a parameter called ‘name’ to a widget that expects a parameter called ‘title’.

You can also declare default values for parameters using hash syntax. You can put #needs declarations on multiple lines or on the same line; the only caveat is that if there are default values, they all have to be at the end of the line (so they go into the magic hash parameter).

If a widget has no #needs declaration then it will accept any combination of parameters just like normal. If a widget wants to declare that it takes no parameters, use the special incantation “needs nil” (and don’t declare any other needs, or kittens will cry).

Usage:

class FancyForm < Erector::Widget
  needs :title, :show_okay => true, :show_cancel => false
  ...
end

That means that

FancyForm.new(:title => 'Login')

will succeed, as will

FancyForm.new(:title => 'Login', :show_cancel => true)

but

FancyForm.new(:name => 'Login')

will fail.



39
40
41
# File 'lib/erector/needs.rb', line 39

def inherited(subclass)
  subclass.needs(*self.get_needs)
end

#needed_defaultsObject



69
70
71
72
73
74
# File 'lib/erector/needs.rb', line 69

def needed_defaults
  @needed_defaults ||= get_needs.inject({}) do |defaults, need|
    defaults = defaults.merge(need) if need.is_a? Hash
    defaults
  end
end

#needed_variablesObject



63
64
65
66
67
# File 'lib/erector/needs.rb', line 63

def needed_variables
  @needed_variables ||= get_needs.map { |need|
    need.is_a?(Hash) ? need.keys : need
  }.flatten
end

#needs(*args) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/erector/needs.rb', line 43

def needs(*args)
  @needs ||= []

  args.each do |arg|
    @needs.push(if arg.nil?
      nil
    elsif arg.is_a? Hash
      arg
    elsif arg.is_a? Symbol
      arg
    else
      fail 'arguments passed to :needs must be Nil, a Hash, or a Symbol'
    end)
  end
end

#needs?(name) ⇒ Boolean

Returns:

  • (Boolean)


76
77
78
# File 'lib/erector/needs.rb', line 76

def needs?(name)
  needed_variables.empty? || needed_variables.include?(name)
end