module Erector::Needs::ClassMethods

Public Instance Methods

get_needs() click to toggle source
# File lib/erector/needs.rb, line 59
def get_needs
  @needs || []
end
inherited(subclass) click to toggle source

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.

# File lib/erector/needs.rb, line 39
def inherited(subclass)
  subclass.needs(*self.get_needs)
end
needed_defaults() click to toggle source
# 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_variables() click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# File lib/erector/needs.rb, line 76
def needs?(name)
  needed_variables.empty? || needed_variables.include?(name)
end