Search code examples
rubysinatrahelper

Pass through another attribute with this helper


I am using Sinatra and an S3 bucket to serve my assets. I have the following helper that assigns the s3 bucket URL as its path but I am wondering how to pass through another attribute, such as width.

helper:

helpers do
  def aws_asset (path)
    File.join settings.asset_host, path
 end
end

config/production:

configure :production do
  set :asset_host, "//#{ENV['FOG_DIRECTORY']}.s3.amazonaws.com/assets/images"
end

to use this helper in my view I can then do this:

<%= image_tag(aws_asset "banner2.jpg") %>

What I want to do though is pass through a width, which I can do with the image_tag alone:

<%= image_tag("banner2.jpg", width: '730px') %>

But if I do:

 <%= image_tag(aws_asset "banner2.jpg", width: '730px') %>

I get wrong number of arguments error, 2 for 1, which I understand as I'm only passing through one attribute.

How can I change the helper to accept a width also?


Solution

  • Maybe you can clean up a bit the (sub)method invocations with some good old parentheses:

    <%= image_tag(aws_asset("banner2.jpg"), width: '730px') %>
    

    In your last snippet, Ruby assumes that you are calling the aws_asset method with 2 arguments: the first being "banner2.jpg" and the second a hash containing width: '730px'