HAML variable Tag ie. %foo or %#{foo} possible? - haml

Is it possible in HAML to create variable TAGs as the subject asks?
Want to do
- tag = "h1"
%tag
Cheers
Final Version I used was
-# Type Default
- if ! defined? locals[ :type ]
- type = "h1"
- else
- type = locals[ :type ]
-# Heading
- haml_tag type do
-# Main Text
= locals[:text]
-# Add the secondary text if required
-if defined? locals[ :small ]
%small= locals[ :small ]

Yeah, it's possible.
Try this.
- tag = 'h1'
- haml_tag tag, "I'm h1."

Related

Rails String Interpolation in Model

I'm trying to string interpolate in a message model.
I want to combine a string 'message' and a select media_url into a :body so I can text a text message that contains both a message and a link concatenated. Any help with the interpolation would be appreciated.
I'm trying to do a before_create to grab two fields and combine them into a 3rd field that's saved as body.
My current result yields:
MESSAGE#{#message.media_url}
message.rb
before_create do
self.body = 'MESSAGE' + '#{#message.media_url}'
end
new.html.erb
<%= f.text_field :body, :value => "body" ,:class => 'form-control ' %>
<%= f.select :media_url, Url.order('name asc').all.collect { |u| [u.name, (u.sanitized_url + u.short_url)] }, { class: 'form-control' } %>
It is suppose to output something like... Message and www.google.com/EdRds which is the value coming from the select box.
Thank you
You got the MESSAGE#{#message.media_url} result, because you're wrapping your #{} in single quotes '', that must be between double quotes.
You could try just interpolating, not concatenating:
before_create do
# Not an instance variable, the media_url attribute from the object itself
self.body = "MESSAGE #{self.media_url}"
end
Because '#{#message.media_url}' won't work as a interpolation, that must be with double quotes "", and 'MESSAGE' + is concatenating the #message.media_url value, so you could wrap all in double quotes and your variable value in {}.

including rails object in meta tags keywords

I'd like to include a rails object in my keywords as well as straight text but the code is clearly not the right way to do it...how can I do this?
set_meta_tags :keywords => %w[keyword1 keyword2 #{params[:hospital]}]
You might want to have a look at two plug-ins for including rails object in meta tags:
Meta Magic: https://github.com/lassebunk/metamagic
Head Liner: https://github.com/mokolabs/headliner
Edit: For Meta tag gem
What I usually do is write a meta helper that I simply stick in my ApplicationHelper, that looks like this:
def meta(field = nil, list = [])
field = field.to_s
#meta ||= {
'robots' => ['all'],
'copyright' => ['My Copyright'],
'content-language' => ['en'],
'title' => [],
'keywords' => []
}
if field.present?
#meta[field] ||= []
case list.class
when Array then
#meta[field] += list
when String then
#meta[field] += [list]
else
#meta[field] += [list]
end
case field
when 'description' then
content = truncate(strip_tags(h(#meta[field].join(', '))), :length => 255)
else
content = #meta[field].join(', ')
end
return raw(%(<meta #{att}="#{h(field)}" content="#{h(content)}"/>))
else
tags = ''
#meta.each do |field, list|
tags += meta(field)+"\n"
end
return tags.rstrip
end
end
You can simply set meta tags in your views, by adding a call to meta() in it. So in an articles/show.html.erb you might add this to the top of your view:
<% meta(:title, #article.title) %>
And in your layouts, you add it without any parameters, so it'll spit out the meta tags.
<%= meta %>
Or have it output an individual tag:
<%= meta(:title) %>
I bet you there's more elegant solutions, though.
But if you were looking for something already implemented in Rails you're out of luck.
Thanks.
Try this in your view as it worked for me (using meta-tags gem):
<% keywords [[#modelname.keyword1], [#modelname.keyword2]] %>
and you cad additional keywords in text format by adding them within the ruby in the following format ['keyword3']

How to remove "=>" from json output in Ruby on Rails 3?

I am stuck with what I think is a simple problem. I am creating json and need to have the format be:
[{ "source" : "google / organic", "visits" : 20 }]
And here is what I get:
[{"source"=>"google / organic", "visits"=>20}]
Here is the model (campaign_results.rb)
def as_json(options = {})
{ "source" => source,
"visits" => visits,
}
end
In the controller:
def show
#campaign_summary = CampaignResults.all
end
In the view:
<%= raw #campaign_summary.as_json %>
Any suggestions on what I should do to replace the "=>" with ":"?
Try calling #to_json:
<%= raw #campaign_summary.as_json.to_json %>

simple_form selected: by name

I have a simple_form collection which contains a list of languages. I want to select 'German' by default, but the selected: option in simple_form requires an id. I could obtain the id of 'German' but would hope that wasn't necessary.
= f.association :language, selected: // not sure what to put here
This works, but stinks (I will NOT be using such atrocious code):
= f.association :language, selected: Language.where("name = 'German'").first.id
I would hope for something like:
= f.association :language, selected: { |lan| lan.name == 'German' }
Every example I've found during the last hour involves the id. Not one example of how to select via the name.
Yeah, SimpleForm can accept proc for selected option. In your case the code is:
= f.association :language, selected: lambda { |lan| lan.name == 'German' }

How to use MongoID validates_inclusion_of

I have a model with a field that can contain a list of values. I want that list to be limited to a subset. I want to use validates_inclusion_of, but probably misunderstand that validation.
class Profile
include Mongoid::Document
field :foo, :type => Array
validates_inclusion_of :foo, in: %w[foo bar]
end
p = Profile.new
p.valid? #=> false; this is correct, as it should fail on empty lists.
p.foo = ["bar"]
p.valid? #=> false; this is incorrect. I would expect it to pass now.
p.errors #=> {:foo=>["is not included in the list"]}
What am I doing wrong? Can validates_inclusion_of be used for arrays?
Your field value is an array (field :foo, :type => Array)
Validation expects field to be not an array to check its inclusion.
By your example validation is checking for ['foo', 'bar'].include?(['bar']) # => false
So correct your :in option in validates_inclusion_of:
validates_inclusion_of :foo, in: [['foo'], ['bar']]