문제

Solution

While on 1.8, i couldnt use the accepted answer directly, but it helped me find the below:

def stylesheet_include(*sources)
  if /^3\.[1-2]/ =~ Rails.version && sources.last.is_a?(Hash)
    sources.last.delete :cache
  end
  stylesheet_link_tag *sources
end

Original question

Working on a modified stylesheet_link_tag helper to pass things properly depending on the rails version, as this map maybe be loaded as an engine in Rails 3.1.x. Here's my code so far, and what i'd like to do:

def stylesheet_include(*sources)
  options = sources.extract_options!.stringify_keys
  if /^3\.[1-2]/ =~ Rails.version
    options.delete "cache"
  end
  stylesheet_link_tag *sources, options
end

The problem is, I cannot pass a second parameter when i call * on the sources variable. I cannot just pass sources, options either, because the link_tag method requires several parameters, not an array. If it receives an array, then you get paths such as: css/reset/css/main.css

Anyone have ideas on how I can get this to work. Worse case scenario I can just not pass the options to it, but i'd rather avoid that.

도움이 되었습니까?

해결책

Actually, if you're using Ruby 1.9, you can indeed have splats before other parameters. Like so:

def stylesheet_include(*sources, options)
  options = sources.extract_options!.stringify_keys
  if /^3\.[1-2]/ =~ Rails.version
    options.delete "cache"
  end
  stylesheet_link_tag *sources, options
end

The problem, of course, is that the last thing you pass to this method will then always become options, even if it isn't a hash. And you can't assign a default to options either, since that behavior would be fairly ambiguous. Thus that solution will work if you always make sure to at least pass an empty hash as the last parameter of stylesheet_include.

If that doesn't work for you, try taking the splat as the parameter and seeing if the last member of the splat is a hash: if so it's your options, if not your options are empty.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top