I can see in the Savon log that my SOAP faults contain XML like this:
<errorCode>666</errorCode><errorDescription>some evil error</errorDescription>
Does anyone know how to parse the error code and description out of the response? Sorry if this is a stupid question, but I've tried everything, and I haven't been able to find any documentation on this.
I have an app where there is always a current contest (defined by start_date and end_date datetime). I have the following code in the application_controller.rb as a before_filter.
def load_contest
@contest_last = Contest.last
@contest_last.present? ? @contest_leftover = (@contest_last.end_date.utc - Time.now.utc).to_i : @contest_leftover = 0
if @contest_last.nil?
Contest.create(:start_date => Time.now.utc, :end_date => Time.now.utc + 10.minutes)
elsif @contest_leftover < 0
@winner = Organization.order('votes_count DESC').first
@contest_last.update_attributes!(:organization_id => @winner.id, :winner_votes => @winner.votes_count) if @winner.present?
Organization.update_all(:votes_count => 0)
Contest.create(:start_date => @contest_last.end_date.utc, :end_date => Time.now.utc + 10.minutes)
end
end
My questions:
1) I would like to change the :end_date to something that signifies next Sunday at a certain time (eg. next Sunday at 8pm). Similarly, I could then set the :start_date to to the previous Sunday at a certain time. I saw that there is a sunday() class (http://api.rubyonrails.org/classes/Time.html#method-i-sunday), but not sure how to specify a certain time on that day.
2) For this situation of always wanting the current contest, is there a better way of loading it in the app? Would caching it be better and then reloading if a new one is created? Not sure how this would be done, but seems to be more efficient.
Thanks!
Hi,
I'm currently integrating facebook into my current app and I've succeeded in retrieving the access_token using the following code:
url="#{url}?#{client_id}&#{client_secret}&#{code}&#{redirect_uri}&type=client_cred"
agent = Mechanize.new
page = agent.get(url)
The page object above has a body which contains text something along the lines of
access_token=XXXXX
I just want to pull out the access_token value. I can get the entire string simply by writing:
page.body
But I was wondering is there a way to get the access_token value without resorting to regular expressions etc?
Thanks.
Hi,
Currently I have an website on a .zip file containing also the .git directory and all the history. I want it to be imported into an Assembla git repository preserving the history of all previous changes. Is there an easy way of doing it?
Well, I`m confused about rails queries. For example:
Affiche belongs_to :place
Place has_many :affiches
We can do this now:
@affiches = Affiche.all( :joins => :place )
or
@affiches = Affiche.all( :include => :place )
and we will get a lot of extra SELECTs, if there are many affiches:
Place Load (0.2ms) SELECT "places".* FROM "places" WHERE "places"."id" = 3 LIMIT 1
Place Load (0.3ms) SELECT "places".* FROM "places" WHERE "places"."id" = 3 LIMIT 1
Place Load (0.8ms) SELECT "places".* FROM "places" WHERE "places"."id" = 444 LIMIT 1
Place Load (1.0ms) SELECT "places".* FROM "places" WHERE "places"."id" = 222 LIMIT 1
...and so on...
And (sic!) with :joins used every SELECT is doubled!
Technically we cloud just write like this:
@affiches = Affiche.all( )
and the result is totally the same! (Because we have relations declared). The wayout of keeping all data in one query is removing the relations and writing a big string with "LEFT OUTER JOIN", but still there is a problem of grouping data in multy-dimentional array and a problem of similar column names, such as id.
What is done wrong? Or what am I doing wrong?
UPDATE:
Well, i have that string Place Load (2.5ms) SELECT "places".* FROM "places" WHERE ("places"."id" IN (3,444,222,57,663,32,154,20)) and a list of selects one by one id. Strange, but I get these separate selects when I`m doing this in each scope:
<%= link_to a.place.name, **a.place**( :id => a.place.friendly_id ) %>
the marked a.place is the spot, that produces these extra queries.
The config/environment.rb of my rails project contains this line:
RAILS_GEM_VERSION = '>= 2.3.2' unless defined? RAILS_GEM_VERSION
Which makes sure that only Rails of version 2.3.2 or greater will be used to run this app.
Is there a way of specifying both the lower and the upper boundary at the same time? So that it would run, say, only on versions higher than 2.3.1 and lower than 2.3.6?
Hi,
i don't understand this little thing:
Suppose, we have "Person" model
class Person < ActiveRecord::Base
end
Why Person.all works ?
Person.all.each { |p| do_something }
This syntax tells us, that we have Person class-object instanciated somewhere ?
Or is it some convention over configuration case ?
Hi,
I'm trying to run a cucumber feature multiple times (i.e 500 times). Is there a way of doing this than me having to type in the same command everytime? I'm guessing this can be done using Rake? I'm not an expert in using rake or cucumber.
Will appreciate your help.
Thanks
Hi,
I have a small question regarding rails. I have a search controller which searches for a name in database, if found shows the details about it or else I am redirecting to the new name page. Is there anyway after redirection that the name searched for to automatically appear in the new form page?
Thanks in advance.
I am trying to model a publications. A publication can have multiple authors and editors. Since it is possible that one person is an author of one publication and an editor of another, no separate models for Authors and Editors:
class Publication < ActiveRecord::Base
has_and_belongs_to_many :authors, :class_name=>'Person'
has_and_belongs_to_many :editors, :class_name=>'Person'
end
The above code doesn't work, because it uses the same join table. Now I now that I can specify the name of the join table, but there is a warning in the API documentation is a warning about that which I don't understand:
:join_table:
Specify the name of the join table if the default based on lexical order
isn’t what you want. WARNING: If
you’re overwriting the table name of
either class, the table_name method
MUST be declared underneath any
has_and_belongs_to_many declaration in
order to work.
I am trying to use some rails code withing a javascript and need to have that rails code be dynamically changed. Here's the line of code:
$(this).replaceWith("<%= escape_javascript(render(:partial => 'shared/products')) %>");
The 'shared/products' is the part I want to change based off information passed earlier in the javascript. How do I insert a value from javascript so that instead of 'shared/products' the products portion can be a variable? Hope this makes sense. I'm not the most experienced jQuery/javascript programmer, so any help is very much appreciated. Thanks in advance!
I'm writing a Sinatra app which needs to render different layouts based on whether the user is using an iPhone or a regular browser. I can detect the browser type using Rack-Mobile-Detect but I'm not sure of the best way to tell Sinatra which layout to use.
Also, I have a feeling that how I choose to do this may also break page caching. Is that true?
Example code:
require 'sinatra/base'
require 'haml'
require 'rack/mobile-detect'
class Orca < Sinatra::Base
use Rack::MobileDetect
helpers do
def choose_layout
if request.env['X_MOBILE_DEVICE'] == :iPhone
# use iPhone layout
else
# use normal layout
end
end
end
before do
# should I use a before filter?
choose_layout()
end
get '/' do
haml :home # with proper layout
end
end #Class Orca
I have a rake task that sends out the next 'x' invitations to join a beta it uses this code:
desc "This will send out the next batch of invites for the beta"
task :send_invites => :environment do
limit = ENV['limit']
c = 0
invitation = Invitation.all(:conditions => { :sent_at => nil, :sender_id => nil }, :limit => limit).each do |i|
Mailer.deliver_invitation(i, register_url(i.token))
c.increment!
end
puts "Sent #{c} invitations."
end
I need to pass in the 'register_url' to the Mailer in order for the link to show up in the email, but since this is running from a rake task and not from a request it does not have a access to the helper methods. What is the best way of achieving this?
I have three models:
Service
has_many :prices
has_many :groups, through: prices
Price
belongs_to :service
belongs_to :group
Group
has_many :prices
I want to have an input field (Simple_Form) for every price.
In views/services/_form.html.haml I do:
simple_form_for @service do |f|
simple_fields_for :groups do |g|
simple_fields_for :prices do |p|
p.input :price
With this setup I only get input fields for already saved prices.
How I can get a price field for every group? I tried to do it manually, but it got really nasty and didn't work either.
Thanks for any ideas!
I want to use selenium test to cover my rails project ! but i just find little documents on selenium test . I want someone to give me some documents for selenium test of all types !like website ,pdf ,text etc. you can sent them to my gmail [email protected] Thank you ,and best regards!
Hi,
I'm looking for suggestions on how to track the number of tags associated with a particular object in Rails. I'm using acts_as_taggable_on and it's working fine. What I would like to be able to do is search for all objects that have no tags, preferably through a scope i.e. Object.untagged.all
My first thought was to use an after_save callback to update an attribute called "taggings_count" in my model:
def update_taggings_count
self.taggings_count = self.tag_list.size
self.save
end
Unfortunately, this does the obvious thing of putting me in an infinite loop. I need to use an after_save callback because the tag_list is not updated until the main object is saved.
Would appreciate any suggestions as I'm on the verge of rolling my own tagging system.
Regards
Robin
Hi all,
I'm trying to post something to an HTTPS resource, but it seems it doesn't work.
My code look something like this:
require 'httparty'
class MyClass
include HTTParty
base_uri "https://mydomain.com:8085/search"
basic_auth 'admin', 'changeme'
format :xml
def mymethod
self.class.post('/job', :query => {:search => "*"})
end
end
As you can see, I've defined an URI with 'https' included, so it should set the use_ssl property for the Net::HTTPS library automatically.
For some reason, Net::HTTP is requested, and I never get in touch with the server, so I end up with an EOF.
Any clues?
I'm trying to implement single-column regionalization for a Rails application and I'm running into some major headaches with a complex SQL need. For this system, a region can be represented by a country code (e.g. us) a continent code that is uppercase (e.g. NA) or it can be NULL indicating the "default" information. I need to group these items by some relevant information such as a foreign key (we'll call it external_id).
Given a country and its continent, I need to be able to select only the most specific region available. So if records exist with the country code, I select them. If, not I want a records with the continent code. If not that, I want records with a NULL code so I can receive the default values.
So far I've figured that I may be able to use a generated CASE statement to get an arbitrary sort order. Something like this:
SELECT *, CASE region
WHEN 'us' THEN 1
WHEN 'NA' THEN 2
ELSE 3
END AS region_sort
FROM my_table
WHERE region IN ('us','NA') OR region IS NULL
GROUP BY external_id
ORDER BY region_sort
The problem is that without an aggregate function the actual data returned by the GROUP BY for a given row seems to be untameable. How can I massage this query to make it return only the first record of the region_sort ordered groups?
When using bundler with a project in general and Rails specifically, you have access only to gems defined in your Gemfile. While this makes sense, it can be limiting. Mostly I find it limiting when I want to use a certain RSpec formatter that the rest of the team doesn't use. Unless it's in the Gemfile, it isn't accessible.
Any way around it or I have to add it to Gemfile?
Update: my problem wasn't Bundler but Spork. When running RSpec without Spork I had no problem of using whatever formatter I wanted.
I am writing a web app to pick random lists of cards from larger, complete sets of cards. I have a Card model and a CardSet model. Both models have a full RESTful set of 7 actions (:index, :new, :show, etc). The CardSetsController has an extra action for creating random sets: :random.
# app/models/card_set.rb
class CardSet < ActiveRecord::Base
belongs_to :creator, :class_name => "User"
has_many :memberships
has_many :cards, :through => :memberships
# app/models/card.rb
class Card < ActiveRecord::Base
belongs_to :creator, :class_name => "User"
has_many :memberships
has_many :card_sets, :through => :memberships
I have added Devise for authentication and CanCan for authorizations. I have users with an 'editor' role. Editors are allowed to create new CardSets. Guest users (Users who have not logged in) can only use the :index and :show actions. These authorizations are working as designed. Editors can currently use both the :random and the :new actions without any problems. Guest users, as expected, cannot.
# app/controllers/card_sets_controller.rb
class CardSetsController < ApplicationController
before_filter :authenticate_user!, :except => [:show, :index]
load_and_authorize_resource
I want to allow guest users to use the :random action, but not the :new action. In other words, they can see new random sets, but not save them. The "Save" button on the :random action's view is hidden (as designed) from the guest users. The problem is, the first thing the :random action does is build a new instance of the CardSet model to fill out the view. When cancan tries to load_and_authorize_resource a new CardSet, it throws a CanCan::AccessDenied exception. Therefore, the view never loads and the guest user is served a "You need to sign in or sign up before continuing" message.
# app/controllers/card_sets_controllers.rb
def random
@card_set = CardSet.new( :name => "New Set of 10", :set_type => "Set of 10" )
I realize that I can tell load_and_authorize_resource to skip the :random action by passing :except => :random to the call, but that just feels "wrong" for some reason.
What's the "right" way to do this? Should I create the new random set without instantiating a new CardSet? Should I go ahead and add the exception?
Here's a common pattern in my controller actions:
respond_to do |format|
format.html {}
format.js {
render :layout => false
}
end
I.e., if the request is non-AJAX, I'll send the HTML content in a layout on a brand new page. If the request is AJAX, I'll send down the same content, but without a layout (so that it can be inserted into the existing page or put into a lightbox or whatever).
So I'm always returning HTML in the format.js portion, yet Rails sets the Content-Type response header to text/javascript. This causes IE to throw this fun little error message:
Of course I could set the content-type of the response every time I did this (or use an after_filter or whatever), but it seems like I'm trying to do something relatively standard and I don't want to add additional boilerplate code.
How do I fix this problem? Alternatively, if the only way to fix the problem is to change the content-type of the response, what's the best way to achieve the behavior I want (i.e., sending down content with layout for non-AJAX and the same content without a layout for AJAX) without having to deal with these errors?
Edit: This blog post has some more info
I'm testing my online store app with RSpec, here's what I'm doing:
# spec/controllers/line_items_controller_spec.rb
require 'spec_helper'
describe LineItemsController do
describe "POST 'create'" do
before do
@current_cart = Factory(:cart)
controller.stub!(:current_cart).and_return(@current_cart)
end
it 'should merge two same line_items into one' do
@product = Factory(:product, :name => "Tee")
post 'create', {:product_id => @product.id}
post 'create', {:product_id => @product.id}
assert LineItem.count.should == 1
assert LineItem.first.quantity.should == 2
end
end
end
# app/controllers/line_items_controller.rb
class LineItemsController < ApplicationController
def create
current_cart.line_items.each do |line_item|
if line_item.product_id == params[:product_id]
line_item.quantity += 1
if line_item.save
render :text => "success"
else
render :text => "failed"
end
return
end
end
@line_item = current_cart.line_items.new(:product_id => params[:product_id])
if @line_item.save
render :text => "success"
else
render :text => "failed"
end
end
end
The problem right now is it never added up two line_items having the same product into one, because the second time I entered into the line_items_controller#create, the current_cart.line_items is [], I have run current_cart.reload to get the test passed, any idea what's going wrong?
I have a query to find all the phone numbers that match a partial expression such as "ends with 234"
@matchingphones = Calls.find :all,
:conditions => [ "(thephonenumber LIKE ?)", "%234"]
The same phone number might be in the database several times, and so might be returned multiple times by this query if it matches.
What I need is to know is UNIQUE phone numbers the query returns.
For example if the database contains
000-111-1234 *
000-111-3333
000-111-2234 *
000-111-1234 *
000-111-4444
the existing query will return the 3 records marked with * (eg returns one phone number -1234 twice since it's in the database twice)
what I need is a query that returns just once instance of each match, in this case
000-111-1234 *
000-111-2234 *