Reputation: 680
What helper can I use in model to populate html code as string in view?
This is the method I currently use in my model:
def state_country_name
"#{self.name} (#{self.country.name})"
end
I want to wrapp {self.country.name}
inside a span, with class: pull-right
.
I have already tried:
def state_country_name
"#{self.name} #{helpers.content_tag(:span, self.country.name, class: "pull-right")}"
end
def helpers
ActionController::Base.helpers
end
Result:
London <span>England</span>
I use the autocomplete-rails4-gem and this is my form input:
= f.input :city_name, :url => autocomplete_city_name_companies_path, :as => :autocomplete, :id_element => "#company_city_id", input_html: {:value => @company.city.name, class: 'form-control'}
Code for my autocomplete_city_name_companies
action:
autocomplete :city, :name, :full => false, :display_value => :state_country_name, :extra_data => [:state_id]
Upvotes: 0
Views: 546
Reputation: 35533
I'd recommend taking the Presenter approach here, as it'll give you a place to put presentation logic that can work with the ruby models but whose logic does not belong in the model itself. You can use Draper or one of several other gems that do this, but here is some code to demonstrate how simple this concept really is:
A sample presenter:
class CompanyPresenter < Struct.new(:company)
def state_country_name
company.country.name
end
# act as proxy for unknown methods
def method_missing(method, *args, &block)
company.public_send(method, *args, &block)
end
end
@presentable_company = CompanyPresenter.new(@company)
Or if you want to take the decorator approach:
module CompanyPresenter
def state_country_name
country.name
end
end
class Company < ActiveRecord::Base
def decorate!
self.extend CompanyPresenter
end
end
@company.decorate!
Upvotes: 2
Reputation: 26
I think you shouldn't do it in your models. Instead put your helpers methods in your helpers file. In your model_helper.rb:
def my_helper(model)
html = <<-EOT
<span class="pull-right">{model.country.name}</span>
EOT
html.html_safe
end
In your view:
<%= my_helper(@model_object) %>
Upvotes: 1