Google Finance currency converter issue in rails - ruby-on-rails-4

I am working on Google currency converter but it's not working. It just redirects to:
http://finance.google.com:80/bctzjpnsun/converter?a=1&from=EUR&to=USD
or it's gives error 404 Not Found
This my code:
gem file:
gem 'money'
gem 'google_currency', '~> 3.4.1'
converter method
def self.exchange_to_USD annual_salary, currency
begin
mothly_salary = annual_salary / 12
if currency.present?
salary = Money.new(mothly_salary, currency).exchange_to(:USD).fractional
else
salary = mothly_salary
end
rescue Money::Bank::UnknownRate => e
salary = mothly_salary
rescue Exception => e
salary = mothly_salary
end
salary
end
application.rb file
require 'money'
require 'money/bank/google_currency'
# set the seconds after than the current rates are automatically expired
# by default, they never expire
Money::Bank::GoogleCurrency.ttl_in_seconds = 86400
# set default bank to instance of GoogleCurrency
Money.default_bank = Money::Bank::GoogleCurrency.new

Use eu_central_bank Instead.
We ended up replacing google_currency with eu_central_bank and it was very easy and worked great. It's part of RubyMoney so it should be well maintained. Basic replacement looks like this:
eu_central_bank = EuCentralBank.new
eu_central_bank.update_rates # TODO: Make this use a cache in a shared directory and just update it every day.
Money.default_bank = eu_central_bank
Definitely a good option to consider.

Google has depreciated that way of retrieving rates. Previously the "bctzjpnsun" link was an alternative way of getting them, but that was switched off recently (possibly on 01-Jun-2018).
You can find some alternative services here: https://stackoverflow.com/a/8391430/6038636

Related

Session variable lost after redirect for feature spec

The session object is cleared after redirect during testing.
First, my test stack. I am running a Rails 4.2.4 app with capybara 2.6.2, capybara-webkit 1.8.0, and rspec 3.3.0. My tests were running without issue until, for no apparent reason whatsoever, they weren't.
Below is my code (condensed to stay on point):
assessment_controller.rb
def create
#assessment_basic = Assessment::Basic.new(params)
if #assessment_basic.valid?
session[:most_recent_zip_code] = #assessment_basic.zip_code
if household.search.present?
update_household_search(#assessment_basic.zip_code)
end
redirect_to dashboard_path
else
render :new
end
end
private
def household
if #household
#household
elsif session[:household_id]
#household = find_household(session[:household_id])
elsif session[:most_recent_zip_code]
#household = Household.create(household_params)
session[:household_id] = #household.id
end
#household
end
As you can see, this is pretty straight-forward. I am receiving a zip code in the params. I store that zip code for later use and use it to create a household object unless one already exists, in which case I return that instance. If a household object is instantiated, I then store its id in the session, return control back to the action and redirect to the dashboard_path having two variables in session. All of this works well, and has worked well for some time now.
However, when I try to access the variables in the dashboard#index action, none of the session variables I stored are present. The feature works, which suggests that my problem is with the bits running my specs. By the way, the spec passes locally. It is when the code is moved to our CI environment that we get the error. We tried three different CI environments (Circle, Semaphore, and Travis) and they all report the same error:
#<NoMethodError: undefined method 'search' for nil:NilClass>
Which basically means, the household could not be recreated and is therefore nil. A closer look shows the reason the household could not be created from session is that the session was cleared.
Can someone help me identify the component(s) involved in ensuring session values persists during tests? Let me know if you need anything else in order to be able to help me.
Hector
it 'a client visits the referrals page with all providers minus the single stop and tax locations from the dashboard page and ' do
user_visits_the_homepage
enter_zip_code('11217', true)
dashboard_page.expect_to_be_on
dashboard_page.click_browse_local_resources
referrals_page.expect_to_be_on
end
def user_visits_the_homepage
visit '/'
expect(page).to have_content t('welcome.where')
end
def enter_zip_code(zip_code = '11217', remain_dashboard = false)
within '.welcome-form:nth-of-type(1)' do
fill_in t('welcome.where'), with: zip_code
click_on t('welcome.get_started')
end
expect(page).to have_content t('header.dashboard')
click_on t('header.your_profile') unless remain_dashboard
expect(page).to have_field t('activerecord.attributes.client_household_member.zip_code'), with: zip_code unless remain_dashboard
end

Save each email before sending rails 4

I want to keep track of all triggered emails by the application into a db table, so that i can have a log which emails are sent and to whom.
Kindly suggest me the best possible solution.
I have solved this using the following way:
created a class in lib directory
class MyProjectMailLogger
def self.delivering_email(message)
#to = message.to.to_s
#subject = message.subject.to_s
#message = message.body.to_s
EmailQueue.create!(:receipient_email => #to, :subject => #subject, :message => #message, :email_status_id => 3)
end
end
In config/initalizers/setup_mail.rb
ActionMailer::Base.register_interceptor(MyProjectMailLogger)
You might need to add the following line in the application.rb file as its not include files from lib directory:
config.autoload_paths += %W(#{config.root}/lib)
Yay!! and i logged my emails.
I am doing some research on this and it seems like https://github.com/ankane/ahoy_email is a nice gem to accomplish this. It uses an interceptor internally like the accepted answer. It also integrates with a free event tracking library that has a number of different backends. Might be something to consider if you're starting something like this today.

Error 404 when i use ActiveResource with Redmine

i have a problem with redmine. In fact, i've created a model who use ActiveResource :
require 'active_resource'
class New < ActiveResource::Base
#self.site = "http://localhost:3000/"
#self.format = :xml
#self.user = 'admin'
#self.password = 'admin'
class << self
attr_accessor :api_key
end
def save
prefix_options[:api_key] = self.class.api_key
super
end
end
New.site = 'http://localhost:3000'
New.api_key = '471bea6d1c4452b82b57287a281ff04392ae4118'
nw = New.new(:field_1 => 'value 1')
nw.save
# Retrieving news
news = New.find(:all)
puts news.first.title
#Retrieving an new
new = New.find(1)
puts new.description
puts new.author.name
# Creating an new
new = New.new(
:project_id => 1,
:author_id => 1,
:title => 'Annonce',
:summary => 'Annonce',
:description => 'Annonce'
)
if new.save
puts new.id
else
puts new.errors.full_messages
end
# Updating an 'new'
new = New.find(1)
new.title = 'NEW INFO '
new.save
# Deleting an new
new = New.find(1)
new.destroy
I'v an error 404 and i don't understand why:
/Users/bj/.rvm/gems/ruby-1.9.3-p429/gems/activeresource-4.0.0/lib/active_resource/connection.rb:144:in `handle_response': Failed. Response code =404. Response message = Not Found . (ActiveResource::ResourceNotFound)
PS: If i use api key or if i use self.site i've a 404 too !
Can you help me please? I tried many things but no every things doesn't works. Thanks for your answers !
The basic problem seems to be, that Redmine is not responding the way ActiveResource expects it. This could be due to changes in Rails 3, that where not properly reflected in Redmine yet.
The best option for you would maybe be dropping ActiveResource for something like httparty. You should also known, that Redmine currently only supports fetching all news (/news.json) and all news within a project (/projects/test_project/news.json). Neither fetching a single news directly nor creating or updating news is supported via the REST API.
Edit: The actual cause for the 404 in your code is due to the fact, that ActiveResource tried to POST to /news.json which is - as I have mentioned above - not supported by the REST API. If you remove the save call, you will run into another issue, where ActiveResource is not able to deserialize the response in New.find(:all). This lead me to think, that Redmine and ActiveResource are currently incompatible. Also the demo code in the Redmine wiki to create an issue, does not work for me.

Amazon Product Advertising API: Get Average Customer Rating

When using Amazon's web service to get any product's information, is there a direct way to get the Average Customer Rating (1-5 stars)? Here are the parameters I'm using:
Service=AWSECommerceService
Version=2011-08-01
Operation=ItemSearch
SearchIndex=Books
Title=A Game of Thrones
ResponseGroup=Large
I would expect it to have a customer rating of 4.5 and total reviews of 2177. But instead I get the following in the response.
<CustomerReviews><IFrameURL>http://www.amazon.com/reviews/iframe?...</IFrameURL></CustomerReviews>
Is there a way to get the overall customer rating, besides for reading the <IFrameURL/> value, making another HTTP request for that page of reviews, and then screen scraping the HTML? That approach is fragile since Amazon could easily change the reviews page structure which would bust my application.
You can scrape from here. Just replace the asin with what you need.
http://www.amazon.com/gp/customer-reviews/widgets/average-customer-review/popover/ref=dpx_acr_pop_?contextId=dpx&asin=B000P0ZSHK
As far as i know, Amazon changed it's API so its not possible anymore to get the reviewrank information. If you check this Link the note sais:
As of November 8, 2010, only the iframe URL is returned in the request
content.
However, testing with the params you used to get the Iframe it seems that now even the Iframe dosn't work anymore. Thus, even in the latest API Reference in the chapter "Motivating Customers to Buy" the part "reviews" is compleatly missing.
However: Since i'm also very interested if its still possible somehow to get the reviewrank information - maybe even not using amazon API but a competitors API to get review rank informations - i'll set up a bounty if anybody can provide something helpful on that. Bounty will be set in this topic in two days.
You can grab the iframe review url and then use css to position it so only the star rating shows. It's not ideal since you're not getting raw data, but it's an easy way to add the rating to your page.
Sample of this in action - http://spamtech.co.uk/positioning-content-inside-an-iframe/
Here is a VBS script that would scrape the rating. Paste the code below to a text file, rename it to Test.vbs and double click to run on Windows.
sAsin = InputBox("What is your ASIN?", "Amazon Standard Identification Number (ASIN)", "B000P0ZSHK")
if sAsin <> "" Then
sHtml = SendData("http://www.amazon.com/gp/customer-reviews/widgets/average-customer-review/popover/ref=dpx_acr_pop_?contextId=dpx&asin=" & sAsin)
sRating = ExtractHtml(sHtml, "<span class=""a-size-base a-color-secondary"">(.*?)<\/span>")
sReviews = ExtractHtml(sHtml, "<a class=""a-size-small a-link-emphasis"".*?>.*?See all(.*?)<\/a>")
MsgBox sRating & vbCrLf & sReviews
End If
Function ExtractHtml(sHtml,sPattern)
Set oRegExp = New RegExp
oRegExp.Pattern = sPattern
oRegExp.IgnoreCase = True
Set oMatch = oRegExp.Execute(sHtml)
If oMatch.Count = 1 Then
ExtractHtml = Trim(oMatch.Item(0).SubMatches(0))
End If
End Function
Function SendData(sUrl)
Dim oHttp 'As XMLHTTP30
Set oHttp = CreateObject("Msxml2.XMLHTTP")
oHttp.open "GET", sUrl, False
oHttp.send
SendData = Replace(oHttp.responseText,vbLf,"")
End Function
Amazon has completely removed support for accessing rating/review information from their API. The docs mention a Response Element in the form of customer rating, but that doesn't work either.
Google shopping using Viewpoints for some reviews and other sources
This is not possible from PAPI. You either need to scrape it by yourself, or you can use other free/cheaper third-party alternatives for that.
We use the amazon-price API from RapidAPI for this, it supports price/rating/review count fetching for up to 1000 products in a single request.

Redmine - Add "Spent Time" Field to Issues Display

How would I go about adding the "Spent Time" as a column to be displayed in the issues list?
Consolidating Eric and Joel's answers, this is what I needed to do to get a 'Spent time' column added to Redmine 1.0.3. Not sure if there's a better way to get the translation text added.
To give the new field a localised name, added to config/locales/en.yml around line 299 at the end of the field definitions:
field_spent_hours: Spent time
To add the new column, created lib/spent_time_query_patch.rb with content:
# Based on http://github.com/edavis10/question_plugin/blob/master/lib/question_query_patch.rb
require_dependency 'query'
module QueryPatch
def self.included(base) # :nodoc:
base.extend(ClassMethods)
# Same as typing in the class
base.class_eval do
unloadable # Send unloadable so it will not be unloaded in development
base.add_available_column(QueryColumn.new(:spent_hours))
end
end
module ClassMethods
unless Query.respond_to?(:available_columns=)
# Setter for +available_columns+ that isn't provided by the core.
def available_columns=(v)
self.available_columns = (v)
end
end
unless Query.respond_to?(:add_available_column)
# Method to add a column to the +available_columns+ that isn't provided by the core.
def add_available_column(column)
self.available_columns << (column)
end
end
end
end
To get the spent_time_query_patch above to actually load, created config/initializers/spent_time_query_patch.rb with content:
require 'spent_time_query_patch'
Query.class_eval do
include QueryPatch
end
You can also do this by adding the column at runtime. This will add the spent hours column without modifying the Redmine core. Just drop the following code into a file in lib/
Adapted from:
Redmine Budget Plugin
Redmine Question Plugin
require_dependency 'query'
module QueryPatch
def self.included(base) # :nodoc:
base.extend(ClassMethods)
# Same as typing in the class
base.class_eval do
unloadable # Send unloadable so it will not be unloaded in development
base.add_available_column(QueryColumn.new(:spent_hours))
end
end
module ClassMethods
unless Query.respond_to?(:available_columns=)
# Setter for +available_columns+ that isn't provided by the core.
def available_columns=(v)
self.available_columns = (v)
end
end
unless Query.respond_to?(:add_available_column)
# Method to add a column to the +available_columns+ that isn't provided by the core.
def add_available_column(column)
self.available_columns
Also, it would be cool, if the column "Spent time" was sortable.
After looking up the produced SQL, I just implemented the sortable feature this in this way:
base.add_available_column(QueryColumn.new(:spent_hours,
:sortable => "(select sum(hours) from time_entries where time_entries.issue_id = t0_r0)")
)
Replace the respective line. I just hope the issue_id column's name is always "t0_r0" ...
PS: You can find lots of examples in app/models/query.rb lines 122++
2-Digits Problem:
Unfortunatly, I had to hack one of the core files: app/helpers/queries_helper.rb
Around line 44, change this:
when 'Fixnum', 'Float'
if column.name == :done_ratio
progress_bar(value, :width => '80px')
else
value.to_s
end
into:
when 'Fixnum', 'Float'
if column.name == :done_ratio
progress_bar(value, :width => '80px')
elsif column.name == :spent_hours
sprintf "%.2f", value
else
value.to_s
end
EDIT: Using a patch instead manipulating the source Recently, we did an update of the redmine system, so the above mentioned Fix also was removed.
This time, we decided to implement that as a patch.
Open up any plugin (We created a plugin for our monkey-patch changes on core). open up vendor/plugins/redmine_YOURPLUGIN/app/helpers/queries_helper.rb
module QueriesHelper
def new_column_content(column, issue)
value = column.value(issue)
if value.class.name == "Float" and column.name == :spent_hours
sprintf "%.2f", value
else
__column_content(column, issue)
end
end
alias_method :__column_content, :column_content
alias_method :column_content, :new_column_content
end
This feature build in from 1.4.0 version
by using AgileDwarf plugin. You can have spent time & you can say for what you spent this time (developement - design -...)
Since no one answered, I just poked the source until it yielded results. Then I started a blog to explain how I did it.
Add spent time column to default issues list in Redmine