I am trying to write Helper method in rails but its throwing error for following line
#if button_source.kind_of?(Array) then list = button_source else list = button_source.sort
The complete code
def buttons(model_name, target_property, button_source)
html = ''
list = ''
if button_source.kind_of?(Array) then list = button_source else list = button_source.sort end
list = button_source.sort
list.each do|x|
html << radio_button(model_name, target_property, x[1])
html << h(x[0])
html << '<br />'
end
return html
end
Please help me to resolve this issue, thanks.
You're missing an end at the end of the if statement.
Related
My text file looks like this
VOTE 1168041805 Campaign:ssss_uk_01B Validity:during Choice:Antony CONN:MIG01TU MSISDN:00777778359999 GUID:E6109CA1-7756-45DC-8EE7-677CA7C3D7F3 Shortcode:63334
VOTE 1168041837 Campaign:ssss_uk_01B Validity:during Choice:Leon CONN:MIG00VU MSISDN:00777770939999 GUID:88B52A7B-A182-405C-9AE6-36FCF2E47294 Shortcode:63334
I want to get value of vote campaign validity choice for which I am doing this:
File.foreach('lib/data/file.txt') do |line|
line = line.tidy_bytes
begin
aline = line.match(/^VOTE\s(\d+)\sCampaign:([^ ]+)\sValidity:([^ ]+)\sChoice:([^ ]+)/)
unless aline.nil?
## do something
end
rescue Exception => e
raise " error: " + e.inspect
p line.inspect
next
end
end
Is there any better way for doing this for
aline = line.match(/^VOTE\s(\d+)\sCampaign:([^ ]+)\sValidity:([^ ]+)\sChoice:([^ ]+)/)
and getting aline[1] aline[2] aline[3] and aline[4]
You can use named captures to get a hash of results instead:
# use a freezed contant instead of making a new Regexp object for each line
REGEXP = /^VOTE\s(?<id>\d+)\sCampaign:(?<campaign>[^ ]+)\sValidity:(?<validity>[^ ]+)\sChoice:(?<choice>[^ ]+)/.freeze
File.foreach('lib/data/file.txt') do |line|
begin
matches = line.tidy_bytes.match(REGEXP)
hash = matches.names.zip(matches.captures).to_h
end
rescue Exception => e
raise " error: " + e.inspect
p line.inspect
next
end
end
If the desired result is an array you might want to use .map:
# use a freezed contant instead of making a new Regexp object for each line
REGEXP = /^VOTE\s(?<id>\d+)\sCampaign:(?<campaign>[^ ]+)\sValidity:(?<validity>[^ ]+)\sChoice:(?<choice>[^ ]+)/.freeze
results = File.foreach('lib/data/file.txt').map do |line|
matches = line.tidy_bytes.match(REGEXP)
matches.names.zip(matches.captures).to_h
end
I have a #page.content that is stored in database as a text column. Is there an easy way to embed a render tag inside that html content?
<div>Lorem ipsum</div>
<%= render 'image_slider' %>
<div>Lorem ipsum</div>
I choose the nokogiri way and finished with two urly helpers
def print_content_start( page, shift=4 )
result = ''
doc = Nokogiri::HTML( page.content )
doc.css('div,p').each_with_index do |node, i|
break if i == shift
result += node.to_s
end
result
end
def print_content_end( page, shift=4 )
result = ''
doc = Nokogiri::HTML( page.content )
doc.css('div,p').drop( shift ).each do |node|
result += node.to_s
end
result
end
If anyone knows a better way, please let me know!
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
I have a controller like this:
def download_link
#It starts a background process to handle all these things
temp_file = Tempfile.new 'temp_file'
temp_sqlite_db = SQLite3::Database.new temp_file.path
temp_sqlite_db.execute("CREATE TABLE inspection (id INTEGER NOT NULL,desc VARCHAR(255));")
inspections = Inspection.a_heavy_query_that_doesnt_worths_to_wait_so_much_for_a_reply
# Some code inserting records and creating tables, with execute() too
# more code, compressing the db and sending an email with a download link to the zip file
end
Now, I would like to know if there's a way to replace the execute() function and maybe create the tables and save records like inspection.create(something) . Thanks in advance
If anyone needs something similar, this was my implementation:
# config/initializers/sql_returner.rb
module ActiveRecord
class Base
def sql_insert
if attributes_with_quotes.empty?
connection.empty_insert_statement(self.class.table_name)
else
"INSERT INTO #{self.class.quoted_table_name} " +
"(#{quoted_column_names.join(', ')}) " +
"VALUES(#{attributes_with_quotes.values.join(', ')});"
end
end
def self.sql_create
"CREATE TABLE #{table_name} (" +
" #{ self.columns.collect{ |column|
column_sql = " #{ column.name } #{ sql_type column } "
column_sql << " PRIMARY KEY " if column.primary
column_sql << " NOT NULL " unless column.null
column_sql
}.join(', ') } );"
end
private
def self.sql_type column
case column.type
when 'datetime', 'string'
'TEXT'
else
column.type.to_s
end
end
end
end
Then, if I need to create tables and insert records, taking the same code of the question as example, I must to run:
def download_link
temp_file = Tempfile.new 'temp_file'
temp_sqlite_db = SQLite3::Database.new temp_file.path
temp_sqlite_db.execute(Inspection.sql_create)
inspections = Inspection.a_heavy_query_that_doesnt_worths_to_wait_so_much_for_a_reply
insert = ""
inspections.each{ |insp|
insert << insp.return_insert_sql
}
#.....
end
For the first method sql_insert I took as example the create method code of ActiveRecord. I know that maybe some kittens died coding this implementation, but at least for me it works.
I would like to enumerate all the URLs in a text string, for example:
text = "fasòls http://george.it sdafsda"
For each URL found, I want to invoke a function method(...) that transforms the string.
Right now I'm using a method like this:
msg = ""
for i in text.split
if (i =~ URI::regexp).nil?
msg += " " + i
else
msg+= " " + method(i)
end
end
text = msg
This works, but it's slow for long strings. How can I speed this up?
I think "gsub" is your friend here:
class UrlParser
attr_accessor :text, :url_counter, :urls
def initialize(text)
#text = parse(text)
end
private
def parse(text)
#counter = 0
#urls = []
text.gsub(%r{(\A|\s+)(http://[^\s]+)}) do
#urls << $2
"#{$1}#{replace_url($2)}"
end
end
def replace_url(url)
#counter += 1
"[#{#counter}]"
end
end
parsed_url = UrlParser.new("one http://x.com/url two")
puts parsed_url.text
puts parsed_url.urls
If you really need extra fast parsing of long strings, you should build a ruby C extension with ragel.