I found this in Ryan Bates' railscast site, but not sure how it works.
#models/comment.rb
def req=(request)
self.user_ip = request.remote_ip
self.user_agent = request.env['HTTP_USER_AGENT']
self.referrer = request.env['HTTP_REFERER']
end
#blogs_controller.rb
def create
@blog = Blog.new(params[:blog])
@blog.req = request
if @blog.save
...
I can sort of understand what he is doing. But am confused with the req=(request) line. Any help is appreciated.
Thanks
Im trying to use rake in a project, and if I put everything into Rakefile it will be huge and hard to read/find things, so I tried to stick each namesapce in its own file in lib/rake, i added this to the top of my rake file:
Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map { |f| require f }
it loads the file no problem, but doesn't have the tasks. I only have one .rake file as a test for now called "servers.rake" and it looks like this:
namespace :server do
task :test do
puts "test"
end
end
so when I run rake server:test id expect to see one line appear saying "test", instead I get
rake aborted!
Don't know how to build task 'server:test'
at first I thought my codes wrong but if I copy the contents of lib/rake/servers.rake into Rakefile it works fine.
How do I get rake tasks to work that are in another file?
Does anybody know of a plug-and-play login system that supports existing logins like Google and OpenID?
I am looking to implement something similar to that of Stack Overflows.
Thanks!
I have some difficulty to extract the total price (css selector = '.total') from the flight result.
http://www.momondo.com/multicity/?Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false#Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false
I get the error "undefined method `text' for nil:NilClass nokogiri ".
My code
desc "Fetch product prices"
task :fetch_details => :environment do
require 'nokogiri'
require 'open-uri'
include ERB::Util
OneWayFlight.find_all_by_money(nil).each do |flight|
url = "http://www.momondo.com/multicity/Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false#Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false"
doc = Nokogiri::HTML(open(url))
price = doc.at_css(".total").text[/[0-9\.]+/]
flight.update_attribute(:price, price)
end
end
You can define a class in a namespace like this
class Gem
class SystemExitException
end
end
or
class Gem::SystemExitException
end
When code uses first method of class definition, ctags indexes the class definition like this:
SystemExitException test_class.rb /^ class SystemExitException$/;" c class:Gem
With the second way, ctags indexes it like this:
Gem rubygems/exceptions.rb /^class Gem::SystemExitException < SystemExit$/;" c
The problem with the second way is that you can't put your cursor (in vim) over a reference to "Gem::SystemExitException" and have that jump straight to the class definition. Your only recourse is to page through all the (110!) class definitions that start with "Gem::" and find the one you're looking for.
Does anyone know of a workaround? Maybe I should report this to the maintainer of ctags?
Greetings,
I have a custom validation in my exemplary Movie model:
class Movie < ActiveRecord::Base
validate :it, :on => :create
private
def it
self.errors.add 'foo', 'bar'
end
end
This works on movie creation but also on updating an existing movie. :on => :update will also work for both. Might that be a bug or am I missing something?
Best regards
Tobias
Hi,
is it possible to set/read cross-domain cookies in Opera browser? I'm using solution http://bit.ly/c1Tk1i (sorry - in Russian, plz use google translate) and it works fine in any browser except Opera.
I have a parent-child relationship between two objects.
Parent :has_many :children
Child :belongs_to :parent
When creating a new parent, in the same controller, I'm creating the child.
@mom = Parent.new
@child = Child.new
@mom.children << @child
That all seems to go okay, but this parent has one more attribute - this parent has a favorite child
@mom.favorite_child = @child
Seems like this should work, except let's say that this is the 61st child in the database, so it gets an ID of 61 (and I know this is happening, because when I check the database, the child record has an ID of 61). For some reason, when I assign the @child to the parent's "favorite_child" attribute, "favorite_child" gets set to "1" - when I need it to be set to "61".
Clues?
8, 10, 12, 981 (few area codes in Sweden). Total phone number can be 10 or 11 (digits only)
If 8 + 9 or 10 digits
if 981 + 7 or 8 digits
Can this be done in regex?
something like that ..hm
(8|10|12)\d{n} = Total Length 10 or 11
When I define the User has_many meetings, it automatically creates a "user_id"
key/value pair to relate to the User collections. Except I can't run any
mongo_mapper finds using this value, without it returning nil or [].
Meeting.first(:user_id = "1234")
Meeting.all(:user_id = "1234")
Meeting.find(:user_id = "1234")
All return nil. Is there another syntax? Basically I can't run a query on the automatically generated associative ObjectId.
# Methods
class User
include MongoMapper::Document
key :user_name, String, :required = true
key :password, String
many :meetings
end
class Meeting
include MongoMapper::Document
key :name, String, :required = true
key :count, Integer, :default = 1
end
# Sinatra
get '/add' do
user = User.new
user.meetings "foobar") #should read: Meeting.new(:name = "foobar")
user.save
end
get '/find' do
test = Meeting.first(:user_id = "4b4f9d6d348f82370b000001") #this is the _id of the newly create user
p test # WTF! returns []
end
The text file has hundreds of these entries (format is MT940 bank statement)
{1:F01AHHBCH110XXX0000000000}{2:I940X N2}{3:{108:XBS/091502}}{4:
:20:XBS/091202/0001
:25:5887/507004-50
:28C:140/1
:60F:C0914CHF7789,
:61:0912021202D36,80NTRFNONREF//0887-1202-29-941
04392579-0 LUTHY + xxx, ZUR
:86:6034?60LUTHY + xxxx, ZUR vom 01.12.09 um 16:28 Karten-Nr. 2232
2579-0
:62F:C091202CHF52,2
:64:C091302CHF52,2
-}
This should go into an Array of Hashes like
[{"1"=>"F01AHHBCH110XXX0000000000"},
"2"=>"I940X N2",
3 => {108=>"XBS/091502"}
etc.
} ]
I tried it with tree top, but it seemed not to be the right way, because it's more for something you want to do calculations on, and I just want the information.
grammar Mt940
rule document
part1:string spaces [:|/] spaces part2:document
{
def eval(env={})
return part1.eval, part2.eval
end
}
/ string
/ '{' spaces document spaces '}' spaces
{
def eval(env={})
return [document.eval]
end
}
end
end
I also tried with a regular expression
matches = str.scan(/\A[{]?([0-9]+)[:]?([^}]*)[}]?\Z/i)
but it's difficult with recursion ...
How can I solve this problem?
I'm trying to do something like the following:
@special_attributes = Model.new.methods.select # a special subset
@special_attributes.each do |attribute|
context "A model with #{attribute}"
setup do
@model = Model.new
end
should "have some special characteristic"
assert @model.method(attribute).call
end
end
end
However, @special_attributes is out of scope when running the unit tests, leaving me with a nil object on line 2. I can't figure out where to define it to bring it in scope. Any thoughts?
Songs on Rap Genius have paths like /lyrics/The-notorious-b-i-g-ft-mase-and-puff-daddy/Mo-money-mo-problems which are defined in routes.rb as:
map.song '/lyrics/:artist_slug/:title_slug', :controller => 'songs', :action => 'show'
When I want to generate such a path, I use song_url(:title_slug => song.title_slug, :artist_slug => song.artist_slug). However, I'd much prefer to be able to type song_url(some_song). Is there a way I can make this happen besides defining a helper like:
def x_song_path(song)
song_path(:title_slug => song.title_slug, :artist_slug => song.artist_slug)
end
Googled for this to no avail. Didn't find anything in the API either. I was expecting some kind of class method or configuration option to set it...
So, rather than calling
from "[email protected]"
for every method, it could be called automatically.
I am getting Encoding::UndefinedConversionError at /find/Wroclaw
"\xC5" from ASCII-8BIT to UTF-8
For some mysterious reason sinatra is passing the string as ASCII instead of UTF-8 as it should.
I have found some kind of ugly workaround... I don't know why Rack assumes the encoding is ASCII-8BIT ... anyway, a way is to use string.force_encoding("UTF-8")... but doing this for all params is tedious
I am using Factory Girl but like the machinist syntax. So I wonder, if there is any way creating a named blueprint for class, so that I can have something like that:
User.blueprint(:no_discount_user) do
admin false
hashed_password "226bc1eca359a09f5f1b96e26efeb4bb1aeae383"
is_trader false
name "foolish"
salt "21746899800.223524289203464"
end
User.blueprint(:discount_user) do
admin false
hashed_password "226bc1eca359a09f5f1b96e26efeb4bb1aeae383"
is_trader true
name "deadbeef"
salt "21746899800.223524289203464"
discount_rate { DiscountRate.make(:rate => 20.00) }
end
DiscountRate.blueprint do
rate {10}
not_before ...
not_after ...
end
Is there a way making factory_girl with machinist syntax acting like that? I did not find one. Help appreciated.
Thx in advance
Jason
read/write_attribute is a great way to enhance default accessors generated by ActiveRecord. Like this for example:
def price
read_attribute(:price) or "This item is priceless and you are by the way #{User.current.login}"
end
The same however does not seem to be working with associations.
Demonstration:
class Product < ActiveRecord::Base
has_and_belongs_to_many :stores
end
Then
>> a = Product.first
=> #<Product id: 1, name: "awesome product", created_at: "2010-05-07 12:11:00", updated_at: "2010-05-07 12:11:00">
>> a.stores
=> [#<Store id: 1, name: "ikea", created_at: "2010-05-07 12:11:28", updated_at: "2010-05-07 12:11:28">]
>> a.read_attribute(:stores)
=> nil
>>
So, is there some sort of read/write_association? Or, if not, is there a reason not to have one?
I'm using the friendly_id gem. I also have my routes nested:
# config/routes.rb
map.resources :users do |user|
user.resources :events
end
So I have URLs like /users/nfm/events/birthday-2009.
In my models, I want the event title to be scoped to the username, so that both nfm and mrmagoo can have events birthday-2009 without them being slugged.
# app/models/event.rb
def Event < ActiveRecord::Base
has_friendly_id :title, :use_slug => true, :scope => :user
belongs_to :user
...
end
I'm also using has_friendly_id :username in my User model.
However, in my controller, I'm only pulling out events pertinent to the user who is logged in (current_user):
def EventsController < ApplicationController
def show
@event = current_user.events.find(params[:id])
end
...
end
This doesn't work; I get the error ActiveRecord::RecordNotFound; expected scope but got none.
# This works
@event = current_user.events.find(params[:id], :scope => 'nfm')
# This doesn't work, even though User has_friendly_id, so current_user.to_param _should_ return "nfm"
@event = current_user.events.find(params[:id], :scope => current_user)
# But this does work!
@event = current_user.events.find(params[:id], :scope => current_user.to_param)
SO, why do I need to explicitly specify :scope if I'm restricting it to current_user.events anyway? And why does current_user.to_param need to be called explicitly? Can I override this?
Hi,
Anyone know how to best implement a multilingual static site using webby?
I would put content for the multiple languages in content/{lang}/{page}.txt for starters, any ideas on the rest?
I've never used webby.
Thanks, Max.
I am trying to test facebook api calls with cucumber. Here is the code.
# app/controller/facebook_users_controller.rb
class FacebookUsersController < ApplicationController
def create
fb_user = facebook_session.user
user = User.new(:facebook_uid => fb_user.uid, :facebook_session_key => facebook_session.session_key
respond_to do |format|
if user.save
format.json { render :json => { :status => 'ok' }.to_json }
end
end
end
end
# features/steps/facebook_connect_step.rb
Given /^I am a facebook connected user$/ do
mock_session = Facebooker::MockSession.create
post('/facebook_user.json')
puts response.code
end
When I run the cucumber step for above step definition, I get a response code of 406 instead of 200. This happens in the cucumber test environment only and not in the browser(development/production).
How do you use gems from a MacRuby .5 application on Snow Leopard? Do I need to specify the gem path? If so, how do I do this?
Best scenario is to package the gems inside the application so the user would not have to install them when the app is distributed.
rdoc --help says:
--accessor, -A accessorname[,..]
comma separated list of additional class methods
that should be treated like 'attr_reader' and
friends. Option may be repeated. Each accessorname
may have '=text' appended, in which case that text
appears where the r/w/rw appears for normal accessors.
Does anyone have any working examples of doing this (both the accessor
method definition and the rdoc command invocation)? No matter what
combination I try, my accessors will not show up in the RDoc output.
Thanks.