Saturday, 15 February 2014

ruby - Local variable is nil, when it clearly shouldn't be (assigned to an expression with itself) -



ruby - Local variable is nil, when it clearly shouldn't be (assigned to an expression with itself) -

why little code snippet (for navigational helper css classes) give me undefined method 'include?' nil:nilclass on elseif-line?

the page_classes_string may 'oddchap oddchap_zoidberg oddchap_zoidberg_index'. think purpose of method clear:

get rid of lastly word in page_classes_string if contains '_index' compare page_classes_string current page_string , homecoming string appropriate class name navigation.

i tried code in irb , of course of study works, not within middleman config. rewrite using 3rd variable gets assigned `page_classes_string', seems kind of cumbersome. suggestions?

of course of study _stringattached next variable names clarification purposes only.

def nav_active(page_string) if page_classes_string.match(/_index/) page_classes_string = page_classes_string.split(/ /)[0..-2].join(' ') end if page_classes_string == page_string 'active' elsif page_classes_string.include? page_string 'semiactive' else nil end end

i suggest getting rid of page_classes_string , create new class hold css classes. depending on how generating page_classes_string, don't imagine disruptive:

class pageclasscollection attr_reader :css_classes def initialize(*classes) @css_classes = classes end def to_s css_classes.join(' ') end def non_index_classes css_classes.select {|c| !c['_index']} end def nav_active?(page_string) homecoming 'active' if non_index_classes == [page_string] homecoming 'semiactive' if non_index_classes.include? page_string nil end end

you utilize this:

page_classes = pageclasscollection.new('oddchap', 'oddchap_zoidberg', 'oddchap_zoidberg_index') page_classes.nav_active?('oddchap') #=> 'semiactive'

if still need convert string, .to_s takes care of (it called automatically if utilize string interpolation, e.g. "#{page_classes}").

ruby middleman

No comments:

Post a Comment