Module: Erector::Needs::ClassMethods
- Defined in:
- lib/erector/needs.rb
Instance Method Summary collapse
- #get_needs ⇒ Object
- #ignore_extra_assigns ⇒ Object
- #ignore_extra_assigns=(new_value) ⇒ Object
- #needed_defaults ⇒ Object
- #needed_variables ⇒ Object
-
#needs(*args) ⇒ Object
Class method by which widget classes can declare that they need certain parameters.
- #needs?(name) ⇒ Boolean
Instance Method Details
#get_needs ⇒ Object
45 46 47 48 49 50 51 52 |
# File 'lib/erector/needs.rb', line 45 def get_needs @needs ||= [] ancestors[1..-1].inject(@needs.dup) do |needs, ancestor| needs.push(*ancestor.get_needs) if ancestor.respond_to?(:get_needs) needs end end |
#ignore_extra_assigns ⇒ Object
69 70 71 |
# File 'lib/erector/needs.rb', line 69 def ignore_extra_assigns @ignore_extra_assigns ||= false end |
#ignore_extra_assigns=(new_value) ⇒ Object
73 74 75 |
# File 'lib/erector/needs.rb', line 73 def ignore_extra_assigns=(new_value) @ignore_extra_assigns = (new_value ? :true : :false) end |
#needed_defaults ⇒ Object
58 59 60 61 62 63 |
# File 'lib/erector/needs.rb', line 58 def needed_defaults @needed_defaults ||= get_needs.inject({}) do |defaults, need| defaults = need.merge(defaults) if need.is_a? Hash defaults end end |
#needed_variables ⇒ Object
54 55 56 |
# File 'lib/erector/needs.rb', line 54 def needed_variables @needed_variables ||= get_needs.map{|need| need.is_a?(Hash) ? need.keys : need}.flatten end |
#needs(*args) ⇒ 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 42 43 |
# File 'lib/erector/needs.rb', line 39 def needs(*args) args.each do |arg| (@needs ||= []) << (arg.nil? ? nil : (arg.is_a? Hash) ? arg : arg.to_sym) end end |
#needs?(name) ⇒ Boolean
65 66 67 |
# File 'lib/erector/needs.rb', line 65 def needs?(name) needed_variables.empty? || needed_variables.include?(name) end |