Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Jam2
Jan 15, 2008

With Energy For Mayhem

manero posted:

Yeah, that's the basic idea. You'll want initialize_region() to return nil in the case that you couldn't initialize the region properly (so your || NullLocale.new falls through properly), but that's the general idea.

Write tests! :science:

It should return the value of @region which is nil if no region matches, right?

Suppose:

class RootController < ApplicationController; end
class ApplicationController < ActionController:: Base; end

Does the filter chain in RootController run before the Applcation controller filter chain? I want to check locale first (before anything happens in any controller). How do I ensure this behavior?

and does initialize_region need to be a private class method?
Ruby code:
undefined method `initialize_region' for Locale:Class
Ruby code:
class Locale

  # must provide session and request options
  def self.new(options = {})
    initialize_region(options) || NullLocale.new
  end

  # return the region object associated with this Locale
  def region_name
    @region.name
  end

  def region_id
    @region.id
  end

  def valid?
    true
  end

  private
  def initialize_region(options = {})
    raise ArgumentError, 'No session provided' if options[:session].nil?
    raise ArgumentError, 'No request provided' if options[:request].nil?

    @region = case
              when Subdomain.matches?(options[:request])
                region = Region.find_by_subdomain(options[:request].subdomain)
                options[:session][:region_id] = region.id if region.present?
                region # @region = region
              else
                Region.find_by_id(options[:session][:region_id])
              end
  end

end

class NullLocale < Locale

  def region_name
    ''
  end

  def region_id
    ''
  end

  def valid
    false
  end

end
I don't think I'm overriding new properly either.

Jam2 fucked around with this message at 21:56 on Aug 7, 2012

Adbot
ADBOT LOVES YOU

manero
Jan 30, 2006

Jam2 posted:

I don't think I'm overriding new properly either.


Nope, you need to do:

Ruby code:
def initialize()
end
For your tests, I would even reconsider exposing @region publicly. If you don't, and you only rely on region_name and region_id methods, your NullLocale doesn't have to worry about exposing a @region object that doesn't make sense.

prom candy
Dec 16, 2005

Only I may dance
You can't return an object of a different class by redefining initialize though, can you? In these situations I usually create a class method that either calls new or returns the null object, and maybe use exceptions and rescue for control flow since you're already kind of doing that:

code:
class Locale
  def self.with(options = {})
    begin
      new(options) 
    rescue ArgumentError
      NullLocale.new
    end
  end
end

manero
Jan 30, 2006

prom candy posted:

You can't return an object of a different class by redefining initialize though, can you? In these situations I usually create a class method that either calls new or returns the null object, and maybe use exceptions and rescue for control flow since you're already kind of doing that:

code:
class Locale
  def self.with(options = {})
    begin
      new(options) 
    rescue ArgumentError
      NullLocale.new
    end
  end
end

Yeah, you're right. It's better to have a separate factory-style method for building what you need with specific rules.

prom candy
Dec 16, 2005

Only I may dance

manero posted:

Yeah, you're right. It's better to have a separate factory-style method for building what you need with specific rules.

Upon looking at it again I might also define and raise my own custom error just so you don't end up inadvertently rescuing something else's ArgumentError.

Bodybuilding Virgin 420
Aug 29, 2000

Check out this Rails/Emberjs site I made. It displays a random tweet from someone
http://givetweet.com/

Switzerland
Feb 18, 2005
Do what thou must do.
I hope I'm not asking too tedious a question, but for those of us who prefer books over online tutorials, what would your book suggestions be for someone who's been messing ONLY with procedural PHP (I know :( ) and wants to level up with RoR, Lucene, MongoDB, and all the other fun buzzwords?

MrDoDo
Jun 27, 2004

You better remember quick before we haul your sweet ass down to the precinct.

Switzerland posted:

I hope I'm not asking too tedious a question, but for those of us who prefer books over online tutorials, what would your book suggestions be for someone who's been messing ONLY with procedural PHP (I know :( ) and wants to level up with RoR, Lucene, MongoDB, and all the other fun buzzwords?

I think its been mentioned on here before but Ruby on Rails 3 Tutorial is pretty solid. I am been meaning to get Rails 3 In Action because it looks like it takes a good end to end approach of an app just like Rails 3 Tutorial.

MrDoDo fucked around with this message at 07:13 on Aug 19, 2012

PhonyMcRingRing
Jun 6, 2002
Is there a way to get authlogic's brute force protection to work with *all* invalid login attempts? Right now it seems to only add to the failed_login_count value if the user tries to login to an actual account but with the wrong password. It completely ignores if the user's trying to login to a non-existent user.

prom candy
Dec 16, 2005

Only I may dance

Bodybuilding Virgin 420 posted:

Check out this Rails/Emberjs site I made. It displays a random tweet from someone
http://givetweet.com/

How did you like working with Emberjs?

Physical
Sep 26, 2007

by T. Finninho
I made a new scaffold and routed it under a :module. After the item saves it redirects to "/" (the site root) instead of the index or show page of the item that was just created. Has this happened to anyone else before? What did I do wrong?

Bodybuilding Virgin 420
Aug 29, 2000

prom candy posted:

How did you like working with Emberjs?

It's pretty awesome. Using handlebars code to update the view didn't work that well for me because it's hard to implement post render hooks but instead I just made my own model observers that update the DOM with some jQuery code. Don't know if that's what they intended but it works for me.

Jam2
Jan 15, 2008

With Energy For Mayhem
I want to use cancan for authorization on my site and force every action to be authorized. I call check_authorization in my ApplicationController and load_and_authorize resource in every controller.

I've generated scaffolds for many of these controllers, so every controller test now fails because they can't authorize. How do I force all of these tests to 'skip_authorization'. I want these scaffold tests to all assume proper authentication. What's the easiest way to accomplish this? I hate the sore sight of failing tests and it's holding back my progress on configuring roles and permissions.

HALP

manero
Jan 30, 2006

Jam2 posted:

I want to use cancan for authorization on my site and force every action to be authorized. I call check_authorization in my ApplicationController and load_and_authorize resource in every controller.

I've generated scaffolds for many of these controllers, so every controller test now fails because they can't authorize. How do I force all of these tests to 'skip_authorization'. I want these scaffold tests to all assume proper authentication. What's the easiest way to accomplish this? I hate the sore sight of failing tests and it's holding back my progress on configuring roles and permissions.

HALP

I just have a login_user method that signs in a specific user from a factory, and different factories that create different kinds of users. Although we don't do all the different permutations of users, usually just one that we know should have access to that action.

Jam2
Jan 15, 2008

With Energy For Mayhem

manero posted:

I just have a login_user method that signs in a specific user from a factory, and different factories that create different kinds of users. Although we don't do all the different permutations of users, usually just one that we know should have access to that action.
Followed the instructions listed below. Authentication does not appear to be happening.

https://github.com/plataformatec/devise/wiki/How-To:-Controllers-and-Views-tests-with-Rails-3-(and-rspec)

Physical
Sep 26, 2007

by T. Finninho
I have a couple models with a "name" or "title" field. What would the syntax look like to ensure uniqueness in those fields across a couple models?
Ruby code:
ModelA
     validates_uniqueness_of :title, :scope => :account_id
end

Jam2
Jan 15, 2008

With Energy For Mayhem
I want to deploy a Rails app to Ubuntu LTS Server. I am using Thin and Postgres in development. I'd like to use nginx, Passenger, and Postgres in production. It seems like rbenv is a suitable way to run ruby in production.

Are there any open-sourced recipes for Chef that come preconfigured to deploy with this pretty basic configuration? What about a Capistrano recipe/script?

This is my first time putting anything in production, so I'd like to keep it simple and automate as much as possible. I will need to migrate from this server within 30-days, so I want to automate as much as possible.

Ideally, I'd like to fork a public repo and make whatever changes I need for my environment. Do these exist?

hepatizon
Oct 27, 2010

Physical posted:

I have a couple models with a "name" or "title" field. What would the syntax look like to ensure uniqueness in those fields across a couple models?
Ruby code:
ModelA
     validates_uniqueness_of :title, :scope => :account_id
end

You'd probably want to use inheritance of some kind. The easiest way is to to create a superclass for the generic validations.

Pardot
Jul 25, 2001




Jam2 posted:

I want to deploy a Rails app to Ubuntu LTS Server. I am using Thin and Postgres in development. I'd like to use nginx, Passenger, and Postgres in production. It seems like rbenv is a suitable way to run ruby in production.

Are there any open-sourced recipes for Chef that come preconfigured to deploy with this pretty basic configuration? What about a Capistrano recipe/script?

This is my first time putting anything in production, so I'd like to keep it simple and automate as much as possible. I will need to migrate from this server within 30-days, so I want to automate as much as possible.

Ideally, I'd like to fork a public repo and make whatever changes I need for my environment. Do these exist?

If you're dead set on running your own stuff, please at least run https://github.com/heroku/wal-e . Having minutely archives of your database will save your rear end.

mmachine
Jan 5, 2006
Just upgraded my VPS dev box to ruby 1.9.3, and I'm now unable to raise site instances using WEBrick. WEBrick starts just fine, I get zero errors, but once I try to hit the site, I get absolutely no response. Tried a few different ports, all had the same issue. Was working just fine before I upgraded to 1.9.3.

I swear, once I upgraded, I rolled a new rails site just to make sure everything was in good order, all was good there, AND and I was able to raise the site no problem. Was only that one time though -- a few minutes later I tried again and that's when the issue popped up...

Any insight into what might have changed during the upgrade to 1.9.3 that I might want to take a peek at?

EDIT: Frustrating... So, this issue literally just fixed itself. Hopped on to give it a second look this afternoon, and WEBrick is responding without any issues - same port, same app, etc.

Still would love to figure out what caused this.

EDIT EDIT: Spoke too soon -- problem's back, same as before. Looks like my box is getting gunked up with WEBrick? Process has been killed -- restarted on the same port it worked with a bit ago, now back to square one -- can't raise a site at all.

Gotta be something obvious I'm doing / not doing...but what?!

mmachine fucked around with this message at 22:44 on Aug 23, 2012

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

How do you guys usually deal with gem dependency conflicts? Specifically,

code:
Bundler could not find compatible versions for gem "faraday":
  In Gemfile:
    zendesk_api (>= 0) ruby depends on
      faraday (>= 0.8.0) ruby

    fbgraph (<= 1.8.0) ruby depends on
      faraday (0.7.6)

Physical
Sep 26, 2007

by T. Finninho

hepatizon posted:

You'd probably want to use inheritance of some kind. The easiest way is to to create a superclass for the generic validations.
Good point but that would be on the "good planning" side of this. How do I do this after the fact, with too much written to go back and change to inheritance. I can just write a function or method, but I was curious how awesome RoR was and if they had something like this built in.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

A MIRACLE posted:

How do you guys usually deal with gem dependency conflicts? Specifically,

code:
Bundler could not find compatible versions for gem "faraday":
  In Gemfile:
    zendesk_api (>= 0) ruby depends on
      faraday (>= 0.8.0) ruby

    fbgraph (<= 1.8.0) ruby depends on
      faraday (0.7.6)

Figure out if fbgraph works with faraday 0.8, fork it, make it so, refer to the fork in your Gemfile until they accept your pull request.

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

Yeah, that's sorta what I thought... thanks.

prom candy
Dec 16, 2005

Only I may dance

Physical posted:

Good point but that would be on the "good planning" side of this. How do I do this after the fact, with too much written to go back and change to inheritance. I can just write a function or method, but I was curious how awesome RoR was and if they had something like this built in.

You're just trying to make sure that across ModelA, ModelB, and ModelC all titles are unique? Totally untested but:

code:
validate :super_unique_title

def super_unique_title
  [ModelA, ModelB, ModelC].each do |klass|
    if klass.find_by_title(title)
      errors.add(:title, "must be unique")
      break
    end
  end
end
Throw that in a module and include it in all 3?

Physical
Sep 26, 2007

by T. Finninho

prom candy posted:

You're just trying to make sure that across ModelA, ModelB, and ModelC all titles are unique? Totally untested but:

code:
validate :super_unique_title

def super_unique_title
  [ModelA, ModelB, ModelC].each do |klass|
    if klass.find_by_title(title)
      errors.add(:title, "must be unique")
      break
    end
  end
end
Throw that in a module and include it in all 3?
That looks like it would do it. Oh and holy poo poo you used it as a validator. Wow, you can write your own validate functions. I swear I have read the docs, but organic stuff like this isn't explicitly stated (though this one is I think). There is alot of fuzzy areas with RoR it seems which makes it very organic but also difficult for me to think of how to accomplish certain things. Your post, for example, opened my eyes on how to use custom functions as validators (which I am pretty sure I read a section on but forgot). At first I read your code and went "meh yea he used a method" but then I realized you tied that to a validate keyword which accomplishes what I was asking for previously. Thank you! Is that bracketed code necessary? [ModelA, ModelB, ModelC]

Here is another question:
How do I make my own, empty, collection object? I'm not really sure how to phrase this for the search engine, but you know how you can do collection = ModelA.where(exp). How do I make the collection object with nothing in it without having to do a Model.find/where etc?

Something like ModelA[] collection in other languages.

See, I am trying to gather a bunch of models of type ModelA, and then I want to sort them asc/desc whatever. So my goal is to fill up the collection object then do collection = collection.sort(:asc) or something like that. At first I used an array, and put models into it by doing collection << _modela but this meant to access things I had to do collection[0][:title] which is bogus. I want to do collection.title and use it like that.

That is all kind of long winded, so tl;dr: How do I make an empty collection object of a certain type of model?

prom candy
Dec 16, 2005

Only I may dance
Model.limit(0)? Model.where("1=1")? Depends on what you're trying to do.

Physical
Sep 26, 2007

by T. Finninho
No that ties it back to the original model. So say I have
Ruby code:
_collection << ModelA.first
_collection << ModelA.last
thing = _collection.find(id);
The "find" does a search on the WHOLE ModelA table. I want to limit the search to just what is in my _collection object.

prom candy
Dec 16, 2005

Only I may dance
What is _collection at this point? Post some real code instead of this pseudo code because I think that there's some stuff that doesn't work behind the scenes the way you're thinking it does.

Physical
Sep 26, 2007

by T. Finninho
I'm not sure what _collection's type is, thats part of what I am asking. I am trying to make a list (glorified array), but with most of the functionality that I get from an ActiveRecord collection. I have an array of all the same type, ModelA. However, I don't want the limited functionality of an array. I want the collection to behave like an ActiveRecords collection, as if I did ModelA.where("mycriteria = 1"). Since the array is all the same type, how do I type cast it to a ModelA collection so I can do things like "item.related_object.title"

This could very likely be something that is not supported, but if it is supported I'd like to learn it.

I'll post some code tommorow if you still need it.

edit: In the meantime I am using an array. But sorting it isn't straight forward. This is giving an error and I don't know why. rating can be nil so that's what the rescues are for.
myarray = myarray.sort{ |a,b| (a.rating rescue 0) <=> (b.rating rescue 0)}
The documentation on this function is zilch.

Physical fucked around with this message at 02:21 on Aug 29, 2012

prom candy
Dec 16, 2005

Only I may dance
It sounds like what you want to do is scope the results of a query. Also if you can't find documentation for something that you're using on an Array or a Hash it's probably because it's getting that functionality from the mixed in Enumerable module, so don't forget to check there.

http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-sort
http://stackoverflow.com/questions/2412340/how-do-you-scope-activerecord-associations-in-rails-3
http://www.railway.at/2010/03/09/named-scopes-are-dead/

I like turtles
Aug 6, 2009

So, I'm interested in Ruby on Rails development - I have quite a bit of experience in Python, but not that much in this sort of web development sphere. I'd do Django, but a lot of the positions coming up I'm interested in seem more interested in RoR.
I am also interested in BDD ala cucumber.

I've been running through the Ruby on Rails tutorial book site thing, and I'm wondering if it is practical/possible/wise to try to come at Ruby on Rails with cucumber directly in the mix right off the bat, or if I should wait and familiarize myself with cucumber later?
If is a good way to go, my very cursory searches haven't shown any substantial or recently updated tutorials on the subject. Anyone have any recommendations on that front?

Doc Hawkins
Jun 15, 2010

Dashing? But I'm not even moving!


The question of whether to teach people Rails first and then how to TDD it, or to teach it all at the same time, seems destined to be a perennial one.

Today, I'm leaning towards the latter, including acceptance tests of the sort that cucumber is used for, but I don't necessarily recommend cucumber itself: for rails I mostly make request specs using rspec and capybara. And recently I've heard of turnip, an rspec extension that interprets the same Given/When/Then language cucumber does.

When I was learning this stuff, I think I got a good start from The Rspec Book (despite the name, covers cucumber, I swear). It hasn't been updated in a while, but (1) if you buy from Pragmatic, you get all future updates for free, and (2) relishapp.com/rspec will catch you up with any changes real quick.

I like turtles
Aug 6, 2009

Ah, cool, ok. Thank you.
I had sort of fixated on Cucumber, but right off the bat the book has RSpec, Capybara, and in a latter section even a chunk on Cucumber.
I'll probably just stick with working through this. http://ruby.railstutorial.org/ruby-on-rails-tutorial-book

PhonyMcRingRing
Jun 6, 2002
So I'm really annoyed with ActiveRecord at the moment. I have a model with a decimal field and I'm finding it impossible to actually validate that field. If I try setting its value to something clearly not a decimal, like "this is not a valid decimal value", something internal to ActiveRecord automatically converts it to a 0 instead. This makes the column "valid" even though a completely invalid value was passed in. How the hell do I get ActiveRecord to properly validate a decimal field instead of converting it to a 0?

EAT THE EGGS RICOLA
May 29, 2008

PhonyMcRingRing posted:

So I'm really annoyed with ActiveRecord at the moment. I have a model with a decimal field and I'm finding it impossible to actually validate that field. If I try setting its value to something clearly not a decimal, like "this is not a valid decimal value", something internal to ActiveRecord automatically converts it to a 0 instead. This makes the column "valid" even though a completely invalid value was passed in. How the hell do I get ActiveRecord to properly validate a decimal field instead of converting it to a 0?

validates_numericality_of ?

Pardot
Jul 25, 2001




That sounds like mysql's default 'helpful' behavior.

PhonyMcRingRing
Jun 6, 2002

EAT THE EGGS RICOLA posted:

validates_numericality_of ?

That doesn't help, I tried it. :/

Basically, I can't do this:
code:
model.decimal_field = 'some poo poo value'
if model.valid?
   puts 'i shouldn't be valid, but I am, cause i became a 0'
else
   puts 'i should fail here'
end

prom candy
Dec 16, 2005

Only I may dance
I'm on my phone with poo poo Internet so I can't look it up but there's something like before_typecast_column that you might be able to use.

Adbot
ADBOT LOVES YOU

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Pardot posted:

That sounds like mysql's default 'helpful' behavior.

It's also how Object#BigDecimal() works, strangely:

code:
0 :> Kernel.BigDecimal "fart"
     # => #<BigDecimal:7ffa7110d740,'0.0',9(9)>
0 :> Kernel.Float "fart"
ArgumentError: invalid value for Float(): "fart"
	from (irb):25:in `Float'
	from (irb):25
	from /Users/bkerley/.rbenv/versions/1.9.2-p290/bin/irb:12:in `<main>'

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply