14b8667b3bdf64068647b96c26001e0d

I have css directives for styling links of the class "squarebutton". I want to be able to pass a custom function 'squarebutton' the standard options that you would pass to 'link_to' but append :class => 'squarebutton' to html_options automatically. I've tried most everything I can think of, but no dice. Any recommendations or alternatives would be awesome. Thanks in advance.

Helper "application_helper.rb'

1
2
3
4
5
def squarebutton(name, options = {}, html_options = nil)
  link_to "<span>#{name.to_s}</span>", options ={}, html_options.merge!{:class => 'squarebutton'}
end

View "some_view.html.erb"

1
2
3
4
<% content_tag :div, :class => 'buttonwrapper' do %>
<%= squarebutton "Delete", person, :confirm => "Are you sure?", :method => :delete %>
<% end %>

Refactorings

No refactoring yet !

6c452e0114832b067300e23b6f83c8e8

Bobby Uhlenbrock

February 26, 2008, February 26, 2008 21:36, permalink

No rating. Login to rate!

Helper

1
2
3
4
5
6
7
8
9
def squarebutton (name, options = {}, html_options = {}, *parameters_for_method_reference)
  newclass = 'squarebutton'
    if html_options.has_key?(:class)
      html_options[:class] << " #{newclass}"
    else
      html_options.merge!({:class => newclass})
    end
    link_to(name, options, html_options, parameters_for_method_reference)
end
6c452e0114832b067300e23b6f83c8e8

Bobby Uhlenbrock

February 27, 2008, February 27, 2008 21:38, permalink

1 rating. Login to rate!

That formatting didn't come through quite right, and I noticed that you are putting the string into a span inside the a tag. This should be better.

Helper "application_helper.rb'

1
2
3
4
5
6
7
8
9
def squarebutton (name, options = {}, html_options = {}, *parameters_for_method_reference)
  newclass = 'squarebutton'
  if html_options.has_key?(:class)
    html_options[:class] << " #{newclass}"
  else
    html_options.merge!({:class => newclass})
  end
  link_to("<span>#{name.to_s}</span>", options, html_options, parameters_for_method_reference)
end
63b22ac9bff0cd55d8a91da4dbf00693

Dan Kubb

February 29, 2008, February 29, 2008 17:17, permalink

1 rating. Login to rate!

This will add the "squarebutton" class to any existing html :class you pass in, as well as work in cases when you don't pass in any :class. content_tag automatically stringifies the name variable, so there's no need to do name.to_s any longer (actually there was never the need, since #{} does the same thing). Also the parameters_for_method_reference arguments passed in other examples have been deprecated in recent versions of Rails, so I chose to leave them out.

1
2
3
4
def squarebutton(name, options = {}, html_options = {})
  html_options[:class] = [ html_options[:class], 'squarebutton' ].compact * ' '
  link_to content_tag(:span, name), options, html_options
end

Your refactoring





Format Copy from initial code

or Cancel