Alter URL using ActiveResource - ruby-on-rails-3

I am using ActiveResource to manage accessing an external service.
The external service has an URL like:
http://api.cars.com/v1/cars/car_id/range/range_num?filter=filter1,filter2
Here's my Car class:
class Car < ActiveResource::Base
class << self
def element_path(id, prefix_options = {}, query_options = nil)
prefix_options, query_options = split_options(prefix_options) if query_options.nil?
"#{prefix(prefix_options)}#{collection_name}/#{URI.parser.escape id.to_s}#{query_string(query_options)}"
end
def collection_path(prefix_options = {}, query_options = nil)
prefix_options, query_options = split_options(prefix_options) if query_options.nil?
"#{prefix(prefix_options)}#{collection_name}#{query_string(query_options)}"
end end
self.site = "http://api.cars.com/"
self.prefix = "/v1/"
self.format = :json
end
When I set up my object to get a particular car in rails console:
> car = car.new
> car.get('1234')
I get a URL like this:
http://api.cars.com/v1/cars//1234.json
How do I get the URL to include the range and range_num elements?
Also, i don't want the .json extension on the end of the URL. I've attempted overriding the element_name and collection_name methods as described here: How to remove .xml and .json from url when using active resource but it doesn't seem to be working for me...
Thanks in advance for any ideas!

Get rid of the forward slash in the URL
"#{prefix(prefix_options)}#{collection_name}/#{URI.parser.escape id.to_s}#{query_string(query_options)}"
becomes:
"#{prefix(prefix_options)}#{collection_name}#{URI.parser.escape id.to_s}#{query_string(query_options)}"

Related

create a (Prawn) PDF inside custom DelayedJob and upload it to S3?

Using: Rails 4.2, Prawn, Paperclip, DelayedJobs via ActiveJobs, Heroku.
I have a PDF that is very large and needs to be handled in the background. Inside a custom Job I want to create it, upload it to S3, and then email the user with a url when its ready. I facilitate this via a PdfUpload model.
Is there anything wrong with my approach/code? Im using File.open() as outlined in examples I found, but this seems to be the root of my error ( TypeError: no implicit conversion of FlightsWithGradesReport into String ).
class PdfUpload < ActiveRecord::Base
has_attached_file :report,
path: "schools/:school/pdf_reports/:id_:style.:extension"
end
/pages_controller.rb
def flights_with_grades_report
flash[:success] = "The report you requested is being generated. An email will be sent to '#{ current_user.email }' when it is ready."
GenerateFlightsWithGradesReportJob.perform_later(current_user.id, #rating.id)
redirect_to :back
authorize #rating, :reports?
end
/ the job
class GenerateFlightsWithGradesReportJob < ActiveJob::Base
queue_as :generate_pdf
def perform(recipient_user_id, rating_id)
rating = Rating.find(rating_id)
pdf = FlightsWithGradesReport.new( rating.id )
pdf_upload = PdfUpload.new
pdf_upload.report = File.open( pdf )
pdf_upload.report_processing = true
pdf_upload.report_file_name = "report.pdf"
pdf_upload.report_content_type = "application/pdf"
pdf_upload.save!
PdfMailer.pdf_ready(recipient_user_id, pdf_upload.id)
end
end
This results in an error:
TypeError: no implicit conversion of FlightsWithGradesReport into String
Changing this:
pdf_upload.report = File.open( pdf )
to this:
pdf_upload.report = StringIO.new(pdf.render)
fixed my problem.

Rails 3: accept all params except a specific value

I have a Rails 3.2.13 Application to maintenance.
Because of authorization rules i want to limit the find(params[:file_registry_id]) method to accept all parameters except 752. (Only user tehen should be able to get it.)
def show
if current_user.tehen?
#file_registry = FileRegistry.find(752)
else
#file_registry = FileRegistry.find(params[:file_registry_id])
end
#rubric = Rubric.find(params[:id])
#rubrics = expanded_rubrics #rubric.ancestors_with_self.collect(&:id)
set_favorites
render :action => 'index'
end
Is there a method available to filter an element (here id 752) from the params hash? Or what's the best way to go?
Simple solution:
def show
#file_registry = get_file_registry
#....
end
private
def get_file_registry
if current_user.tehen?
FileRegistry.find(752)
else
unless params[:file_registry_id] == FORBIDDEN_ID_FOR_GUEST
FileRegistry.find(params[:file_registry_id])
else
false
end
end
end
FORBIDDEN_ID_FOR_GUEST should be defined outside of the controller, for example inside of a initializer.
But I suggest to use a authorization library like CanCan (https://github.com/ryanb/cancan) where you can define permissions for every use case.

Rails / Sitemap_Generator: Subdomain sitemaps

I'm trying to create a sitemap for my app which features subdomains using the sitemap_generator gem. However, I'm getting an error with my code:
the scheme http does not accept registry part: .foo.com (or bad hostname?)
My sitemap.rb:
SitemapGenerator::Sitemap.default_host = "http://www.foo.com"
SitemapGenerator::Sitemap.sitemaps_host = "http://s3.amazonaws.com/foo/"
SitemapGenerator::Sitemap.public_path = 'tmp/'
SitemapGenerator::Sitemap.sitemaps_path = 'sitemaps/'
SitemapGenerator::Sitemap.adapter = SitemapGenerator::WaveAdapter.new
SitemapGenerator::Sitemap.create do
add '/home'
end
Customer.find_each do |customer|
SitemapGenerator::Sitemap.default_host = "http://#{customer.user_name}.foo.com"
SitemapGenerator::Sitemap.sitemaps_path = "sitemaps/#{customer.user_name}"
SitemapGenerator::Sitemap.create do
add '/home'
end
end
What am I doing wrong?
I'm the author of this gem.
I am fairly certain that the problem is with one of the customer user name's containing a character which is not allowed in a URL. A simple test with simple names works e.g.:
%w(bill mary bob).each do |customer|
SitemapGenerator::Sitemap.default_host = "http://#{customer}.foo.com"
SitemapGenerator::Sitemap.sitemaps_path = "sitemaps/#{customer}"
SitemapGenerator::Sitemap.create do
add '/home'
end
end

Rails helper method method not works in PDF if sending as an attachment

Hi i have create a PDF conversion in my rails application using Prawn and it working fine.
Now i am sending that PDf in an email attachment. Now problem is that i can send PDF attachment if i do not use any helper method, but when i use my format_currency method in PDf file it gives error on instance_eval method. here is my code sample:
format currency code:
module ApplicationHelper
def format_currency(amt)
unit = 'INR'
country = current_company.country
if !country.blank? && !country.currency_unicode.blank?
unit = country.currency_unicode.to_s
elsif !country.blank?
unit = country.currency_code.to_s
end
number_to_currency(amt, :unit => unit+" ", :precision=> 2)
end
end
My controller code :
pdf.instance_eval do
#company = current_company
#invoice = invoice
#invoice_line_items = invoice_line_items
#receipt_vouchers = receipt_vouchers
eval(template) #this evaluates the template with your variables
end
the error message i got :
undefined method `format_currency' for #<Prawn::Document:0x7f89601c2b68>
with this code i can send attachment successfuly if i don't use helper method but i need to use that method.
I have fixed this issue in a different manner, i have created a new currency_code method in my company model and called that in my format_currency helper method and it is working for me fine:
Here is what i have done :
def currency_code
unit = 'INR'
if !country.blank? && !country.currency_unicode.blank?
unit = country.currency_unicode.to_s
elsif !country.blank?
unit = country.currency_code.to_s
end
unit
end
and used it in my format_currency helper :
def format_currency(amt)
unit = current_company.currency_code
number_to_currency(amt, :unit => unit+" ", :precision=> 2)
end
and in my controller i have added a variable for currency and used it in my pdf file:
pdf.instance_eval do
#company = current_company
#invoice = invoice
#invoice_line_items = invoice_line_items
#receipt_vouchers = receipt_vouchers
#currency = current_company.currency_code # new added variable for currency
eval(template) #this evaluates the template with your variables
end

Why is my Rails model custom setter/getter method failing?

what am I doing wrong here?
I have a model for an app I am writing called page. Those attributes are:
title
pagetype
page_url
title and pagetype can be set as normally, but I used a custom getter/setter for the page_url. Here is the logic/model:
class Page < ActiveRecord::Base
def page_url=()
temp = self[:title]
pageUrl = temp.gsub(" ", "_").downcase
if self[:pagetype] == "home"
pageUrl = "/"
end
self[:page_url] = pageUrl
end
def page_url
self[:page_url]
end
end
It's fairly simple -> page_url is based on the title with all spaces replaced with unless page_type == "home", which then gets set to "/". For the record I don't want to make page_url virtual because I need it to be searchable and saved in the db.
So unfortunately whether in rails console or my app this is failing. Here is how I am calling the setter method in the console;
page1 = Page.new
page1.pagetype = "home"
page1.title = "this is a test"
page2 = Page.new
pager2.pagetype = "content"
page2.title = "this is another test"
#expected results should be
page1.page_url()
=> "/"
page2.page_url()
However I keep getting this:
page1.page_url()
=> nil
What the heck am I doing wrong here?
These custom setter and getters don't persist to the database. If you have a column page_url in your database, you can set the value with a callback. E.g. before_save:
class Page < ActiveRecord::Base
before_save :set_page_url
def set_page_url
if self[:pagetype] == "home"
self.page_url = "/"
else
self.page_url = self[:title].gsub(" ", "_").downcase
end
end
end