Simple string concatenation in rails in view page - ruby-on-rails

I am new to Rails. Can someone please explain to me the concept of string concatenation using variables in view page and the controller?

For example :
In controller Code :
def show
#firstname = 'Test'
#lastname = 'User'
end
In view page :
Full Name : <%= "#{#firstname} #{lastname}" %>
For further details Click Here
Scenarios:- If you want to keep two variables on View page and add concatenation for those then use of space is necessary.
View page:
<%
var string_1 = "With"
var string_2 = "Rails"
var addition_1 = string_1 + string_2;
var addition_2 = string_1 + " " + string_2
%>
<h1> First Addition -> #{addition_1} </h1>
<h1> Second Addition -> #{addition_2} </h1>
Output :
First Addition -> WithRails
Second Addition -> With Rails

in view
<%
var1 = "ruby"
var2 = "on"
var3 = var1 + var2
%>
Finally
<% f_var = "Ruby #{var3}"%>
but this type of code is not recommended in view as it does not look good. You should use helper method for this type of requirement

Related

How to push a blank name and a name on to this array in Rails

I have an array of names. I want the first option to be blank, and the last option to be "Joe".
Here is the code:
def index
#case_managers = client.personnel_search_by_client(current_client.client_id, nil, groupMnemonic: 'reimbursement_whitelist')
#case_managers_drop_down = {}
#case_managers.each do |case_manager|
#case_managers_drop_down[case_manager.name] = case_manager.to_json
end
end
In my views I have:
= form_tag work_lists_path, :method=> 'put' do |f|
.fieldset.field-group.field-group-inline.pull-left
.field.field-text.field-required
%label= t('workflow.duplicate_claim_manager')
= select_tag('case[case_manager]', options_for_select(#case_managers_drop_down, #selected_case_manager))
This correctly gets all the names. I thought before the array I would do something like #case_managers_drop_down.push(" ") to get a blank option and then likewise for Joe. But this doesnt seem to be working. Any idea on how I can append to this array?
To get a blank option at first place in select_tag use include_blank boolean attribute like :
= select_tag('case[case_manager]', options_for_select(#case_managers_drop_down, #selected_case_manager), :include_blank => true)
OR use prompt like :
= select_tag('case[case_manager]', options_for_select(#case_managers_drop_down, #selected_case_manager), :prompt => "Please select")
For last option as joe do it like :
def index
#case_managers = client.personnel_search_by_client(current_client.client_id, nil, groupMnemonic: 'reimbursement_whitelist')
#case_managers_drop_down = {}
#case_managers.each do |case_manager|
#case_managers_drop_down[case_manager.name] = case_manager.to_json
end
#case_managers_drop_down["joe"] = ""
end
Hopefully it will work!

How do I send information from controller method to HTML page?

I am developing a Rails application and want to put some info that I already read from an XML file and show it in a new page.
In my view I have:
<%= link_to 'Hoteles', :method => :hotels %>
and the controller method is:
def hotels
url = "http://api.hotelsbase.org/search.php?longitude="+#city_visit.longitude+"&latitude="+#city_visit.latitude
data = Nokogiri::HTML(open(url))
$name = data.xpath("//name")
$fulladdress = data.xpath("//fulladdress")
$phone = data.xpath("//phone")
$city = data.xpath("//city")
$description = data.xpath("//description")
$featured = data.xpath("//featured")
$stars = data.xpath("//stars")
$rating = data.xpath("//rating")
$long = data.xpath("//long")
$lat = data.xpath("//lat")
$dist = data.xpath("//dist")
$price = data.xpath("//price")
$tripadvisorurl = data.xpath("//tripadvisorurl")
$url = data.xpath("//url")
$hotelsbaseUrl = data.xpath("//hotelsbaseUrl")
end
Now I want to show that information in a HTML page.
All the global variables (starting with a $) you've defined should be instance variables (starting with an #)
#name = data.xpath("//name")
#fulladdress = data.xpath("//fulladdress")
And then you can use them in the hotels.html.erb view, like this
<%= #name %>
You should look at Rails guides to find more information and good practices about Rails; the one called "Layouts and Rendering in Rails" would have helped you for this question.

Write simple rails code better

I'm newbie on rails.
In my form I get string like "123, xxx_new item, 132, xxx_test "
if the item start with "xxx_" than its mean that i should add the item to the db otherwise enter the value
this is my code and i sure that there is a better way to write this code
tags = params[:station][:tag_ids].split(",")
params[:station][:tag_ids] = []
tags.each do |tag|
if tag[0,4] =="xxx_"
params[:station][:tag_ids] << Tag.create(:name => tag.gsub('xxx_', '')).id
else
params[:station][:tag_ids]<< tag
end
end
I'm looking for how to improve my code syntax
What about:
tags = params[:station][:tag_ids].split(',')
params[:station][:tag_ids] = tags.each_with_object([]) do |tag, array|
array << tag.start_with?('xxx_') ? Tag.create(name: tag[4..-1]).id : tag
end

Generate table of contents like on Wikipedia, without JavaScript

I have a page that is formatted like so:
<h1>Header</h1>
<h2>Subheader</h2>
<h3>Subsubheader</h3>
<h1>Another header</h1>
Is it possible to server-side generate a table of contents / outline at the start of the page, like Wikipedia does in its articles? I use Ruby on Rails.
EDIT: WITHOUT JavaScript!
I created a class for this purpose today. It depends on http://www.nokogiri.org/, but that gem comes with Rails already.
Put this in app/models/toc.rb:
class Toc
attr_accessor :html
TOC_CLASS = "toc".freeze
TOC_ELEMENT = "p".freeze
TOC_ITEMS = "h1 | h2 | h3 | h4 | h5".freeze
UNIQUEABLE_ELEMENTS = "h1 | h2 | h3 | h4 | h5 | p".freeze
def initialize(content)
#html = Nokogiri::HTML.fragment content
end
def generate
clear
set_uniq_ids
toc = create_container
html.xpath(TOC_ITEMS).each { |node| toc << toc_item_tag(node) }
html.prepend_child toc
return html.to_s
end
private
def clear
html.search(".#{TOC_CLASS}").remove
end
def set_uniq_ids
html.xpath(UNIQUEABLE_ELEMENTS).
each { |node| node["id"] = rand_id }
end
def rand_id
(0...8).map { ('a'..'z').to_a[rand(26)] }.join
end
def create_container
toc = Nokogiri::XML::Node.new TOC_ELEMENT, html
toc["class"] = TOC_CLASS
return toc
end
def toc_item_tag(node)
"<a data-turbolinks='false' class=\"toc-link toc-link-#{node.name}\" href=\"##{node["id"]}\">#{node.text}</a>"
end
end
Use it like
toc = Toc.new article.body
body_with_toc = toc.generate
article.update body: body_with_toc
You need to generate data source from your hierarchy to be something like this
#toc = [ ['header', 0], ['subheader', 1], ['subsubheader', 2],
['header2', 0], ['header3', 0], ['subheader2', 1]
]
Than it is easy to render it in template, for example:
<%- #toc.each do |item, distance| %>
<%= (' ' * distance * 5).html_safe %>
<%= item %>
<br/>
<%- end %>
Would give you:
header
subheader
subsubheader
header2
header3
subheader2
Of course you can use 'distance' for determining style size instead of 'depth', but I hope you get the main idea.
yes, it is possible. you don't really need rails for this; you can also use javascript to generate a table of contents.
Here is an exmaple library that you can use.
http://www.kryogenix.org/code/browser/generated-toc/
You could alternatively create your anchor links as you loop through elements in your rails erb/haml views.

using url in a string in ruby

I want to convert urls in a string to workable urls. For example:
str = "Hello, this is the link for yahoo: http://www.yahoo.com"
//in the view i have
<%= parse_description(r[:description]) %>
//in helper, i am splitting each word in the string and verifying if i have a string which
// contains http, if http is present then i am using link_to to make it a valid url:
def parse_description(str)
s = ""
str.split.each do |w|
a = w.include?("http") ? (link_to nil,"#{w}") : w
s += "#{a} "
end
end
once the string is returned back to the view, the link is not clickable. what wrong i am doing?
Thanks pst for your help.. while returning i just did s.html_safe.. it worked.
To match the URI's in a String use the following code:
html_string.scan(URI.regexp) do |*matches|
p $&
end

Resources