Ym4r can't convert to string for rails3 - ruby

Here's some background of my problem:
I am on Snow Leopard
I have RVM installed(using a ruby1.9.2-head installation)
I am using rails3
I installed the ym4r using this http://github.com/guilleiguaran/ym4r_gm (and followed the tutorial)
Anyway, I added these to my controller:
#map = GMap.new("map_div")
#map.control_init(:large_map => true,:map_type => true)
#map.center_zoom_init([75.5,-42.56],4)
#map.overlay_init(GMarker.new([75.6,-42.467],:title => "Hello", :info_window => "Info! Info!"))
then these to my view:
Test <%= raw(GMap.header) %> <%= raw(#map.to_html) %> <%= raw(#map.div(:width => 600, :height => 400)) %>
well actually im using haml(does it matter?)
Test
= raw(GMap.header)
- unless #map.blank?
= raw(#map.to_html)
#map{:style => "width: 600px; height: 400px"}
problem is i keep getting a
Showing /Users/eumir/rails_apps/evo-lux/app/views/layouts/_map.html.haml where line #11 raised:
can't convert Ym4r::GmPlugin::Variable to String (Ym4r::GmPlugin::Variable#to_str gives Ym4r::GmPlugin::Variable)
Extracted source (around line #11):
9: Test
10: = raw(GMap.header)
11: = raw(#map.to_html)
12: = raw(#map.div(:width => 600, :height => 400))
which is totally weird. I can't double check with debugger(it's another error altogether...my rails cant find ruby-debugger)
so im really kinda stumped. Any help?

The following function needs to be added to class Variable in mapping.rb of the plugin.
def to_str
#variable + ";"
end
Array#* gets called in the to_html function and Ruby 1.9.2 uses to_str instead of to_s to join the values.

Ok should've RTFM. Some discoveries:
the plugin was made for the now deprecated google maps v2 API
the to_html function of the plugin is a bit off in the sense that the init variables for the html variables is an array of variables - which are being joined by a string.

Related

Ruby HAML add If Condition to each.do

I have a haml ruby site that is pulling data from Salesforce. What I need to be able to do is to set an if condition based on the productCode listed in SF. The each.do establishes a loop to display the related data for each record in the loop.
The client would like productFamily specific pages. So I need to loop through all items with a product code of GEA for one page and GFE for another page.
.row
.col-xs-12
- #price_book.where(:productCode => GEA).each do |prod|
.row
.panel.panel-default
.panel-body
.col-xs-4
%img{:src => "#{prod.productUrl}", :height => "200", :width => "150"}
When I attempt to run this I get the following error:
ActionView::Template::Error (uninitialized constant ActionView::CompiledTemplates::GEA):
7:
8: .row
9: .col-xs-12
10: - #price_book.where(:productcode => GEA).each do |prod|
11:
12: .row
13: .panel.panel-default
Thank You for your assistance, I am new to Ruby and modifying another Developers code.
If #price_book is an ActiveRecord::Relation object, not just array of YourModel and productcode is String column of YourModel then you can call additional ActiveRecord methods like where:
#price_book.where(:productcode => 'GEA')
If GEA, GFE are not variables defined in view then values should be in quotes (double quotes) 'GEA', "GFE".
You can put
= #price_book.inspect
in your template and get more info about it. Tell us what kind of object is #price_book and we will give you advice.
I was able to apply the if filter logic to the loop with the following modification to the code
- #price_book.select{ |prod| prod[:productCode] == "GEA" }.each do |prod|
This returned only items from the price book with a product code of GEA

watir webdriver using a variable

I am having trouble using a variable in browser reference. I am trying to pass the field type such as ul, ol etc. The code works if I type ol, but I would like to use the pass variable labeled 'field'. I recieve an "undefined method for field" error.
I have tried also using #{field}, but that does not work either. The error is that field is not defined.
def CheckNewPageNoUl(browser, field, text1, output)
browser.a(:id => 'submitbtn').hover
browser.a(:id => 'submitbtn').click
output.puts("text1 #{text1}")
browser.body(:id => 'page').wait_until_present
if browser.table.field.exists?
output.puts(" #{text1} was found in CheckNewPageNoUl")
end
end
field = "ol"
text1 = "<ol>"
CheckText.CheckNewPageNoUl(b, field, text1, outputt)
To translate a string into a method call, use Object#send, which can take two parameters:
The method name (as string or symbol)
Arguments for the method (optional)
Some examples:
field = 'ol'
browser.send(field).exists?
#=> Translates to browser.ol.exists?
specifiers = {:text => 'text', :class => 'class'}
browser.send(field, specifiers).exists?
#=> Translates to browser.ol(:text => 'text', :class => 'class').exists?
For your code, you would want to have:
if browser.table.send(field).exists?
output.puts(" #{text1} was found in CheckNewPageNoUl")
end

Rails 3.1 form_for missing method

I'm working with a model that I know is working (records exist in the data base, can be searched for and displayed in other views, etc.) but when I try to use the form_for tag to generate a view for editing one of these records, I get an error message:
Showing /var/www/caucus/app/views/registration_loader/checkIn.html.erb where line #13 raised:
undefined method `voter_path' for #<#<Class:0x98cabdc>:0x98c8878>
Extracted source (around line #13):
10: </div>
11:
12: <%= form_for(
13: #voter,
14: { :controller => "registration_loader",
15: :action => "editVoter"
16: } ) do |f| %>
The #voter refers to a Voter object retrieved by:
# Get the voter.
#voter = Voter.where( [ "voter_id = ?", #voterId ] )[ 0 ]
if not #voter
flash[ :error ] = "NO VOTER!"
redirect_to :action => 'search'
elsif not #voter.kind_of?( Voter )
flash[ :error ] = "NO VOTER RECORD! (#{#voter.class.to_s})"
redirect_to :action => 'search'
end
When I change the #voter to :voter, it stops giving me the error, but does not populate the fields in my view with the data for the record I want to edit.
According to the Rails 3.1 API guide, passing a model object into form_for should generate code that allows me to edit the data in that object, but evidently there is a missing helper method (voter_path). Where is this voter_path method supposed to be defined, and what is its proper semantic and signature? Nowhere in the documentation is creating such a method discussed, nor can I find any examples of writing such a method.
Is the *_path method supposed to be auto-generated? If not, can someone point me to the documentation that specifies the syntax and semantics of this method?
Thanks,
John S.
Short answer: don't use form_for unless you have also designed your code to use "resourceful controllers". Use form_tag instead. Adding resources :voters to routes creates routes to a non-existent controller.

Is sprintf incompatible with sinatra?

Say I have this:
class Account
...
property :charge, Decimal, :precision => 7, :scale => 2
...
classy stuff
...
def self.balance(prefix)
x = Account.get(prefix.to_sym).order(:fields => [:charge]).sum(:charge)
sprintf("%5.2f", x)
end
end
(Edit: The value of all :charge fields is 0.13E2 (0.1E2 + 0.3E1). This is correctly returned. Only in a View does it seem to get borked from sprintf)
In IRB Account.balance(:AAA) returns => "13.00"
if I call Account.balance(:AAA) from a view I get TypeError at /accounts
can't convert nil into Float
Account.balance(:AAA) works anywhere I call it except in a view. If I remove sprintf("%5.2f", x) I get 0.13E2 in my view. (using Account.balance(:AAA).to_f in a view gives me 13.0)
Is sinatra incompatible with sprintf? or am I not understanding how to use sprintf?
(Edit: This is the offending view:)
<section>
<% #accounts.each do |account| %>
<article>
<h2><%= account.prefix %></h2>
<span><p>This account belongs to <%= account.name %> & has a balance of $<%= Account.balance(account.prefix) %>.</p></span>
</article>
<% end %>
</section>
Wouldn't it make more sense to define balance as an instance method rather than a class method? It looks from your example like you're calling balance in an account-specific way anyway, so why not make it:
# the model
class Account
#...
def balance
amount = self.order(:fields => [:charge]).sum(:charge)
sprintf "%5.2f", amount
# or the infix version:
"%5.2f" % amount
end
end
,
# the view
...balance of $<%= account.balance %>...
I know that this doesn't address sprintf per se, but the problem is more likely to be coming from the slightly convoluted lookup than from a built-in method. Even if my specific code doesn't suit your application, it might be worth simplifying the lookup step, even if that involves a few more lines of code.
The advantage of this approach is that there is no doubt that you'll be getting the right Account record.
tested it with a little sinatra app and it worked for me
app.rb
#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'
get '/' do
#x = 10.23
erb :index
end
views/index.erb
<%= sprintf("%5.2f", #x) %>
output:
10.23
ruby 1.9.2 / sinatra 1.3.1
I think there is another error before the sprintf because of your error message:
can't convert nil into Float
seems like your x is nil. try to be sure that x is not nil there, then sprintf should work as expected.

Ruby on Rails - Truncate to a specific string

Clarification: The creator of the post should be able to decide when the truncation should happen.
I implemented a Wordpress like [---MORE---] functionality in my blog with following helper function:
# application_helper.rb
def more_split(content)
split = content.split("[---MORE---]")
split.first
end
def remove_more_tag(content)
content.sub(“[---MORE---]", '')
end
In the index view the post body will display everything up to (but without) the [---MORE---] tag.
# index.html.erb
<%= raw more_split(post.rendered_body) %>
And in the show view everything from the post body will be displayed except the [---MORE---] tag.
# show.html.erb
<%=raw remove_more_tag(#post.rendered_body) %>
This solution currently works for me without any problems.
Since I am still a beginner in programming I am constantly wondering if there is a more elegant way to accomplish this.
How would you do this?
Thanks for your time.
This is the updated version:
# index.html.erb
<%=raw truncate(post.rendered_body,
:length => 0,
:separator => '[---MORE---]',
:omission => link_to( "Continued...",post)) %>
...and in the show view:
# show.html.erb
<%=raw (#post.rendered_body).gsub("[---MORE---]", '') %>
I would use just simply truncate, it has all of the options you need.
truncate("And they found that many people were sleeping better.", :length => 25, :omission => '... (continued)')
# => "And they f... (continued)"
Update
After sawing the comments, and digging a bit the documentation it seems that the :separator does the work.
From the doc:
Pass a :separator to truncate text at a natural break.
For referenece see the docs
truncate(post.rendered_body, :separator => '[---MORE---]')
On the show page you have to use gsub
You could use a helper function on the index page that only grabs the first X characters in your string. So, it would look more like:
<%= raw summarize(post.rendered_body, 250) %>
to get the first 250 characters in your post. So, then you don't have to deal w/ splitting on the [---MORE---] string. And, on the show page for your post, you won't need to do anything at all... just render the post.body.
Here's an example summarize helper (that you would put in application_helper.rb):
def summarize(body, length)
return simple_format(truncate(body.gsub(/<\/?.*?>/, ""), :length => length)).gsub(/<\/?.*?>/, "")
end
I tried and found this one is the best and easiest
def summarize(body, length)
return simple_format = body[0..length]+'...'
end
s = summarize("to get the first n characters in your post. So, then you don't have to deal w/ splitting on the [---MORE---] post.body.",20)
ruby-1.9.2-p290 :017 > s
=> "to get the first n ..."

Resources