Adding a Key to csv erb template output - ruby-on-rails

Currently in my create.csv.erb template I have this.
<%- event_headers = #event_filters -%>
<%= CSV.generate_line(event_headers) %>
It generates a CSV file like this
event1,event2,event3,event4
I would like to add some sort of Key or header, so that the output looks like this
Events: event1,event2,event3,event4
or like this
Events:
event1,event2,event3,event4
is this possible?

Use string interpolation to construct string you wish to have :)
<%= "Events: #{CSV.generate_line(event_headers)}" %>

Related

Add arbitrary string to URLs in Rails/Middleman app

I'm using middleman to generate a static webpage. I need to add a consistent but understandable string to all urls so I can understand how users navigate on the page.
Now i do it like this
<% link_to '/'+?button=navigation , class: 'logotype', itemprop: 'url' do %>
...
<% end %>
I would prefer not having to manually add all the parameters but rather just use something that's already there, like a scope or something. I was thinking about using the name of the template file for example. The url is not unique enough.
Any suggestions?
The standard way of doing this would be to write a helper method that encapsulates your functionality:
<%= link_to_as_nav('/', class: 'logotype', ...) do %>
...
<% end %>
Then write a helper method:
def link_to_as_nav(url, options)
link_to(url + '?button=navigation', options)
end
This is the naïve approach and won't account for a url argument that already has parameters added, but that's something you can work to fix.

Custom Sublime Snippets - HTML Style Formatting

Forgive the vague title, I'm having a hard time figuring out the correct phrase for what I am trying to do.
I have a number of custom snippets I have written to support writing ERB for Ruby on Rails. For this example, I am trying to use an if tag that can be on a single line:
<% if something %>Content Here<% end %>
or multiple lines with indented content:
<% if something %>
Content Here
<% end %>
I am able to get the first (single line) format working fine with the following snippet:
<![CDATA[<% if $1 %>${2:$SELECTION}<% end %>$0]]>
The problem is that if I type in the trigger, hit tab, type in the conditional for $1, hit tab, then hit return, Sublime does exactly what I type and puts the following:
<% if something %>
[cursor]<% end %>
Is there a way in the snippet to instead treat the if and end tags like HTML tags:
<% if something %>
[cursor]
<% end %>
Thanks!
The easiest way is to define a new snippet with a new tabTrigger. It will look something like:
<snippet>
<content><![CDATA[<% if $1 %>
${2:$SELECTION}
<% end %>$0]]>
</content>

Ruby on Rails puts in erb

I'm working on a web application that has a view where data is fetched and parsed from a text file (the textfile is only available at the backend, not to the user). I've written a function that takes in the text file and converts it to an array of strings, it's called txt_to_arr. Then I have another function line_fetcher which just calls txt_to_arr and outputs a random string from the array.
In my view, I call the controller's function as so: <% line_fetcher %>.
I've put both txt_to_arr and line_fetcher into the view controller's helper rb file, and when I run rails s, the random string is not rendered at all. I've also tried <% puts line_fetcher %>
I've checked in Bash that the function does output random strings from the text file, so the function does work correctly. Also, the text file being parsed is in the public folder. Does anyone have an idea why this might be?
Thanks a lot!
Try placing the code in the controller and assigning the output to a variable using
a=`line_fetcher` (note the backtics) as detailed at
http://rubyquicktips.com/post/5862861056/execute-shell-commands
and then <%= a %> in your view.
and place the file in the root of your rails app
Simple erb like <%= line_fetcher %> would work good for simple variables.
But if you want output of any model/database instance then do:
<%= ModelName.first.inspect %>
Note the inspect word.
And in case of using HAML do:
=ModelName.first.inspect
In ERB: The <% %> signify that there is Ruby code here to be interpreted. The <%= %> says interpreted and output the ruby code, ie display/print the result.
So it seems you need to use the extra = sign if you want to output in a standard ERB file.
<%= line_fetcher %>
Use <%= %> to output something in your view, so:
<%= line_fetcher %>

How can i list Cassandra cql result? Do i have to parse JSON?

How can i parse my json style result from Cassandra?
I'm using the cassandra-cql gem for rails and i want to parse the query result to list all messages. My query looks like:
def self.get_messages uid
##db.execute("SELECT * FROM messages WHERE uid=?", uid)
end
how can i list all messages? My current view is:
<% json_dec = ActiveSupport::JSON.decode(u.row.to_json) %>
<% json_dec.each do |f| %>
<%= f[1] %><br/>
<%end%>
and it returns:
1
[{"name"=>"uid", "value"=>"1", "timestamp"=>-1}, {"name"=>"1326751801", "value"=>"test content", "timestamp"=>1326751801970000}, {"name"=>"1326754147", "value"=>"some content to test", "timestamp"=>1326754147612000}]
Is there any better way for the query? how do others solve this problem?
Encoding to json and the decoding again doesn't make much sense. Instead you can call #to_hash on the row object which will give you a hash of column_name => value. Then you could iterate over that:
<% row.to_hash.each do |key, value| %>
<p>key: <%= key %>, value: <%= value %></p>
<%end%>
It also looks like you need to change your implementation of get_message to call fetch:
def self.get_messages uid
##db.execute("SELECT * FROM messages WHERE uid=?", uid).fetch
end

using a conditional statement modifier in Rails Templates

I have a rails template (.rhtml file) generating a Javascript object. It looks something like the following:
var volumes = {
<% for volume in #volumes %>
<%= volume.id %> : <%= volume.data %>
<%= ',' unless volume === #volumes.last %>
<% end %>
};
Note the unless statement modifier to suppress printing the comma after the last element (to satisfy Internet Explorer, which incredibly doesn't support trailing commas in JSON properties declarations).
This appears to work, but as a matter of style, do people think it is reasonable to rely on <%= value unless condition %> in the template generating an appropriate render call?
I don't see why not, but generally if you find yourself conditionalizing a comma on the last member, you probably want to use join instead:
<%= #volumes.map {|v| "#{v.id} : #{v.data}"}.join "," %>
If you would like to contruct JSON (and BTW you are constructing JavaScript Object not Array) then I suggest to use to_json method:
var volumes = <%= #volumes.inject({}){|h,v| h.merge(v.id=>v.data)}.to_json %>;
or
var volumes = <%= Hash[*#volumes.map{|v| [v.id, v.data]}.flatten].to_json %>;
Even better would be to move Ruby Hash construction to model as it is too complex for view.
class Volume
def self.to_hash(volumes)
Hash[*volumes.map{|v| [v.id, v.data]}.flatten]
end
end
and then in view you can put much simpler code:
var volumes = <%= Volume.to_hash(#volumes).to_json %>;
Or even:
<%= #volumes.map { |v| "#{v.id} : #{v.data}"}.to_sentence -%>
To get "a: something, b: something else, c: anything, and d: another thing."

Resources