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
KoRMaK
Jul 31, 2012



Arachnamus posted:

Splatting args turns a set of discrete args into an array. If you want to pass them to another method as args (and not an array) you need to unsplat them, thus:

Ruby code:
def split(*args)
  self.to_s.split(*args)
end
Thank you so much for the quick reply.

Adbot
ADBOT LOVES YOU

xtal
Jan 9, 2011

by Fluffdaddy
This is real pedantry but the self is unnecessary in that code. You can just use to_s.split.... You only need to use the self-dot notation to differentiate from local variables.

Also, it's good practice to capture and pass on the block when making delegating functions. You might as well use *args, &blk in all cases.

xtal fucked around with this message at 19:36 on Aug 26, 2014

KoRMaK
Jul 31, 2012



xtal posted:

This is real pedantry but the self is unnecessary in that code. You can just use to_s.split.... You only need to use the self-dot notation to differentiate from local variables.
Don't worry about it, I like hearing this stuff.

...I use self like this. I just don't feel safe not using it.

xtal posted:

Also, it's good practice to capture and pass on the block when making delegating functions. You might as well use *args, &blk in all cases.
What? Can you give me a code example of what that would look like?

xtal
Jan 9, 2011

by Fluffdaddy

KoRMaK posted:

Don't worry about it, I like hearing this stuff.

...I use self like this. I just don't feel safe not using it.

What? Can you give me a code example of what that would look like?

Ruby code:
def receiver(uno, dos, &blk)
  # do some stuff
end

def delegator(*args, &blk)
  receiver(*args, &blk)
end
Same concept as your code, but also passing along the block. The ampersand is used to (a) capture references to blocks on the receiver (b) pass along blocks on the sender, much like the asterisk either packs or unpacks depending on where you use it.

&blk (which could be &anything) stands in competition to yield. The difference is that yield will fail if there is no block, and the block is not assigned to a variable. With &blk, the block isn't required (the variable will be set to nil) and you have a named function object that you can wrap or pass on to other functions.

When you call something with an ampersand argument it means "try to convert this object to a Proc, then pretend that Proc is a block I've just sent you." Symbols implement to_proc, which is why you can use select(&:positive?).

xtal fucked around with this message at 20:05 on Aug 26, 2014

KoRMaK
Jul 31, 2012



xtal posted:

Ruby code:
def receiver(uno, dos, &blk)
  # do some stuff
end

def delegator(*args, &blk)
  receiver(*args, &blk)
end
Same concept as your code, but also passing along the block. The ampersand is used to (a) capture references to blocks on the receiver (b) pass along blocks on the sender, much like the asterisk either packs or unpacks depending on where you use it.

&blk (which could be &anything) stands in competition to yield. The difference is that yield will fail if there is no block, and the block has no name, so you can't pass it around or wrap it or anything. With &blk, blk will be set to nil if a block isn't sent, and you can pass blk, a Proc object, to other functions (just like it was the original block) by using the ampersand.

Consider that when you use select(&:positive?), the ampersand sends to_proc to :positive (which returns a proc that sends positive to its argument.) Then, it sends along that proc with the ampersand, meaning the receiving function will consider it to be a block.
I'm not following what you are getting at. How would this have improved what I wrote? Can you rephrase your example in the context of the example I gave?

xtal
Jan 9, 2011

by Fluffdaddy

KoRMaK posted:

I'm not following what you are getting at. How would this have improved what I wrote? Can you rephrase your example in the context of the example I gave?

I reworded my post a bit, not that it made a substantial difference. The idea is basically that if you're making a delegating function with *args, there's no downside to sending along the &block in addition. It'll save headaches down the road, and the delegator doesn't need to know what the receiver does or doesn't support -- it should pass along everything and the receiver should validate it.

KoRMaK
Jul 31, 2012



xtal posted:

I reworded my post a bit, not that it made a substantial difference. The idea is basically that if you're making a delegating function with *args, there's no downside to sending along the &block in addition. It'll save headaches down the road, and the delegator doesn't need to know what the receiver does or doesn't support -- it should pass along everything and the receiver should validate it.
I don't get what the blk would contain? the to_s.split() part?

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

enraged_camel posted:

Thank you guys. I'm no longer contemplating suicide. :gbsmith:

Also, don't hand-configure any servers, use Chef or Puppet or Ansible or literally anything that requires you to keep your server configurations in Git and lets you build a new server in minutes instead of hours.

DONT THREAD ON ME
Oct 1, 2002

by Nyc_Tattoo
Floss Finder
a

DONT THREAD ON ME fucked around with this message at 03:17 on Oct 8, 2014

DONT THREAD ON ME
Oct 1, 2002

by Nyc_Tattoo
Floss Finder
In other news, I figured out that erb will let you do this:

code:
<%- 
def render_details(details)
  details.each do |k,v|
-%> 
    <details>
      <summary>
        <%= k.to_s %>
      </summary>
        <div style="padding-left:30px">
<%-   
          if v.class == Hash
            render_details(v)
          else 
-%>
            <%= v %>
<%-       end 
%> 
      </div>
    </details>
<%- 
  end 
end
render_details({omg: {look: "it's", at: :loving }, becky: { this: :bad, code: "!!!" } }  )
%>

The Journey Fraternity
Nov 25, 2003



I found this on the ground!
PHP thread is thataway

necrotic
Aug 2, 2005
I owe my brother big time for this!

MALE SHOEGAZE posted:

In other news, I figured out that erb will let you do this:

code:
<%- 
def render_details(details)
  details.each do |k,v|
-%> 
    <details>
      <summary>
        <%= k.to_s %>
      </summary>
        <div style="padding-left:30px">
<%-   
          if v.class == Hash
            render_details(v)
          else 
-%>
            <%= v %>
<%-       end 
%> 
      </div>
    </details>
<%- 
  end 
end
render_details({omg: {look: "it's", at: :loving }, becky: { this: :bad, code: "!!!" } }  )
%>

Why wouldn't it? You could probably do it in haml, too. But... Why?

Chilled Milk
Jun 22, 2003

No one here is alone,
satellites in every home

MALE SHOEGAZE posted:

In other news, I figured out that erb will let you do this:

code:
<%- 
def render_details(details)
  details.each do |k,v|
-%> 
    <details>
      <summary>
        <%= k.to_s %>
      </summary>
        <div style="padding-left:30px">
<%-   
          if v.class == Hash
            render_details(v)
          else 
-%>
            <%= v %>
<%-       end 
%> 
      </div>
    </details>
<%- 
  end 
end
render_details({omg: {look: "it's", at: :loving }, becky: { this: :bad, code: "!!!" } }  )
%>

You're a bad man for even joking about this

DONT THREAD ON ME
Oct 1, 2002

by Nyc_Tattoo
Floss Finder

necrotic posted:

Why wouldn't it? You could probably do it in haml, too. But... Why?

Because partials are obviously not enough for people, so I constantly see object methods that return "HMTL CODE".html_safe, which are then rendered in the view. I'm just surprised I haven't seen this.

You could even say, define a bunch of these methods in your application.html.erb then use them whenever you want!

kayakyakr
Feb 16, 2004

Kayak is true
you have made me hurt. hurt bad.



So, if anyone needs a senior level rails consultant, I'll have 20-40 hours/month starting in September. Yo.

KoRMaK
Jul 31, 2012



MALE SHOEGAZE posted:

In other news, I figured out that erb will let you do this:

code:
<%- 
def render_details(details)
  details.each do |k,v|
-%> 
    <details>
      <summary>
        <%= k.to_s %>
      </summary>
        <div style="padding-left:30px">
<%-   
          if v.class == Hash
            render_details(v)
          else 
-%>
            <%= v %>
<%-       end 
%> 
      </div>
    </details>
<%- 
  end 
end
render_details({omg: {look: "it's", at: :loving }, becky: { this: :bad, code: "!!!" } }  )
%>

...oh. OHHHH

Now I see whats going on. And its recursive.

I inherited RoR code that was written by some offshore people who obviously mainly program in VB. All the variables had poo poo like arrVariable in front of it (arr for Array) instead of just pluralized variable names to signify a collection. Weird loops and stuff, and badly designed everything.

I never want to go back to VB or C# or .Net for work stuff.

fantastic in plastic
Jun 15, 2007

The Socialist Workers Party's newspaper proved to be a tough sell to downtown businessmen.
I have a weird situation with ActiveRecord associations, and since Rails is fighting me tooth and nail on what I'm trying to do, I get the sense I might be approaching it the wrong way. (Class names have been changed to protect the innocent.)

I have a chain of has_many through, like so:

code:
class Industry
	has_many :companies
	has_many :employees through: :companies
	has_many :dogs through: :employees
end

class Company
	belongs_to :industry
	has_many :employees
	has_many :dogs through: employees
end

class Employee
	belongs_to :company
	has_many :dogs
end

class Dog
	belongs_to :employee
end
Industry has a property 'name' which is just a string, like widgets. Dog has a bunch of properties like breed, color, is_fuzzy, and so on.

What I want to do is have a method on Dog that finds all of the dogs that match the parameters passed in, all of which are optional. One of those parameters can be an industry name, so the method could find all is_fuzzy poodles where the related industry is widgets.

I approached making a search that can find various Dogs like this:

code:
class Dog < ActiveRecord::Base
  def self.filter(attributes)
    attributes.inject(self) do |scope, (key, value)|
      return scope if value.blank?
      case key.to_sym
      when :id, :breed 
        scope.where(key => value)
      when :is_fuzzy
	scope.where("is_fuzzy = ?", is_fuzzy)
      when :min_age
        scope.where("age >= ?", min_age)
      when :max_age
	scope.where("age <= ?", max_age)
      else
        scope
      end 
    end  
  end
end
However, for the life of me I can't figure out how to also implement the parameter from the Industry class. Since it's not a part of the Dog database I can't just query for it with a .where. Is using scopes the wrong approach, and, if so, what would work better?

fantastic in plastic fucked around with this message at 02:26 on Aug 27, 2014

KoRMaK
Jul 31, 2012



Tao Jones posted:

Since it's not a part of the Dog database I can't just query for it with a .where. Is using scopes the wrong approach, and, if so, what would work better?
You mean they are in different Database or different tables?

This is the kind of thing that would get handled with a join.

fantastic in plastic
Jun 15, 2007

The Socialist Workers Party's newspaper proved to be a tough sell to downtown businessmen.

KoRMaK posted:

You mean they are in different Database or different tables?

This is the kind of thing that would get handled with a join.

They're all different tables in the same database, sorry.

Safe and Secure!
Jun 14, 2008

OFFICIAL SA THREAD RUINER
SPRING 2013

Arachnamus posted:

You can't. Rails validations are always at risk for race conditions when not backed by database constraints.

Hm. What kind of constraint would work conditionally, only taking effect when we try insert something that is flag to disallow duplicates?

necrotic
Aug 2, 2005
I owe my brother big time for this!

MALE SHOEGAZE posted:

Because partials are obviously not enough for people, so I constantly see object methods that return "HMTL CODE".html_safe, which are then rendered in the view. I'm just surprised I haven't seen this.

You could even say, define a bunch of these methods in your application.html.erb then use them whenever you want!

That entire idea really belongs in the coding horrors thread.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Safe and Secure! posted:

Hm. What kind of constraint would work conditionally, only taking effect when we try insert something that is flag to disallow duplicates?

A unique index:
Ruby code:
class AddPartNumberToProducts < ActiveRecord::Migration
  def change
    add_column :products, :part_number, :string
    add_index :products, :part_number, unique: true
  end
end

Safe and Secure!
Jun 14, 2008

OFFICIAL SA THREAD RUINER
SPRING 2013
That won't work. That applies to part_number all the time. It has to apply conditionally and such a thing is not doable through a unique index in MySql.

Safe and Secure! fucked around with this message at 13:39 on Aug 27, 2014

kayakyakr
Feb 16, 2004

Kayak is true

Safe and Secure! posted:

That won't work. That applies to part_number all the time. It has to apply conditionally and such a thing is not doable through a unique index in MySql.

track a secondary field that has a uniqueness constraint set to allow nils. if it meets the condition, mirror the property onto that field. If it does not, then leave that field blank.

i'd also consider playing around with a multi-column unique index where the additional column is a value based on your conditional. Unless your conditional is simply checking the presence of a field, in which case why aren't you using multi-column unique indexes?

Jaded Burnout
Jul 10, 2004


Tao Jones posted:

However, for the life of me I can't figure out how to also implement the parameter from the Industry class. Since it's not a part of the Dog database I can't just query for it with a .where.

Join ye a table:

code:
> Query.joins(:bets).where(:'bets.link' => Bet.last.link).count
   (0.6ms)  SELECT COUNT(*) FROM `queries` INNER JOIN `bets` ON `bets`.`query_id` = `queries`.`id` WHERE `bets`.`link` = '/government/ministers/minister-of-state-for-disabled-people'
 => 2 
Since you're building a fairly standard filtering system, I'd be wondering if someone had already written a gem to do this.

Jaded Burnout fucked around with this message at 17:50 on Aug 27, 2014

Safe and Secure!
Jun 14, 2008

OFFICIAL SA THREAD RUINER
SPRING 2013

kayakyakr posted:

track a secondary field that has a uniqueness constraint set to allow nils. if it meets the condition, mirror the property onto that field. If it does not, then leave that field blank.

i'd also consider playing around with a multi-column unique index where the additional column is a value based on your conditional. Unless your conditional is simply checking the presence of a field, in which case why aren't you using multi-column unique indexes?

A multi-column unique index won't work. My conditional could be changed to checking the presence of a field (using NULL instead of one of the two values), but we still want to prevent the insertion of ('TitleA', false) even when ('TitleA', NULL) is in the table.

fantastic in plastic
Jun 15, 2007

The Socialist Workers Party's newspaper proved to be a tough sell to downtown businessmen.

Arachnamus posted:

Join ye a table:

Thanks, this was just what I needed to get myself unstuck. :)

Pardot
Jul 25, 2001




Safe and Secure! posted:

That won't work. That applies to part_number all the time. It has to apply conditionally and such a thing is not doable through a unique index in MySql.

I don't know how feasible it is in your situation, but if you can do a migration to postgres, you could have partial unique indexes which would solve your problem. create unique index on book (Title) where (not DuplicateTitleAllowed)

EVGA Longoria
Dec 25, 2005

Let's go exploring!

Anyone know of a Warden strategy compatible with Devise::Strategies::DatabaseAuthenticatable? I'm investigating moving authentication off Rails to Sinatra, so Devise itself is out.

It's not a terribly complicated strategy, but I wanted to double check if anyone knew of an existing one before I built it.

xenilk
Apr 17, 2004

ERRYDAY I BE SPLIT-TONING! Honestly, its the only skill I got other than shooting the back of women and calling it "Editorial".
More a REST question (followed by a breadcrumb question) than a rails question but what rules do you guys applies when it comes to REST routes?

I'm trying to optimize the way I do my routes

Here are my relationships so far:

An account has many projects
A project belongs to one account and has many units
A unit belongs to one project and has many leases
A lease belongs to one unit and has many events and many payments
A payment belongs to a lease
An event belongs to a lease


I read that ideally it shouldn't be deeper than 2 levels

so do those route make sense?

/accounts/
/account/X/
/account/X/projects/
/project/X
/project/X/units
/project/X/unit/Y/ (this shows the unit details + leases)
/lease/X/ (this shows the lease + payments/events)
/lease/X/event/Y/
/lease/X/payment/Y/


Also, regarding breadcrumbs, I figure I need to gather all information. Right now I'm doing it in the controller with a before_filter :init_parents function that looks just like that

code:
  def init_parents
    @lease = Lease.includes(:followups).find(params[:lease_id])
    @door = Door.find(@lease.door)
    @project = Project.find(@door.project)
  end
Am I right in thinking that this isn't optimal and/or should be in the model instead?

EAT THE EGGS RICOLA
May 29, 2008

I agree with most of this post about designing APIs

xenilk
Apr 17, 2004

ERRYDAY I BE SPLIT-TONING! Honestly, its the only skill I got other than shooting the back of women and calling it "Editorial".
Hi guys, small brain fart ...

I have two model functions that goes like this:

code:
  #return the active leases
  def active_lease
  	Lease.where("door_id = ? AND date_start <= now() AND date_end >= now()", self.id).first
  end

  #look if the door has any active lease/tenant
  def has_active_lease?
  	!self.active_lease.nil?
  end
It works fine, but am I right to think that "!self.active_lease.nil?" isn't elegant?

Chilled Milk
Jun 22, 2003

No one here is alone,
satellites in every home

xenilk posted:

Hi guys, small brain fart ...

I have two model functions that goes like this:

code:
  #return the active leases
  def active_lease
  	Lease.where("door_id = ? AND date_start <= now() AND date_end >= now()", self.id).first
  end

  #look if the door has any active lease/tenant
  def has_active_lease?
  	!self.active_lease.nil?
  end
It works fine, but am I right to think that "!self.active_lease.nil?" isn't elegant?
Well for starters you can use active_lease.present?

http://railsless.blogspot.com/2011/08/difference-between-nil-empty-blank.html

Chilled Milk fucked around with this message at 19:53 on Aug 31, 2014

Jaded Burnout
Jul 10, 2004


xenilk posted:

Hi guys, small brain fart ...

I have two model functions that goes like this:

code:
  #return the active leases
  def active_lease
  	Lease.where("door_id = ? AND date_start <= now() AND date_end >= now()", self.id).first
  end

  #look if the door has any active lease/tenant
  def has_active_lease?
  	!self.active_lease.nil?
  end
It works fine, but am I right to think that "!self.active_lease.nil?" isn't elegant?

If you just want something falsey, go with active_lease, otherwise !!active_lease is a common way to get an actual true/false. Otherwise use active_lease.present? which pretty much does the same thing but requires activesupport: https://github.com/rails/rails/blob...blank.rb#L4-L25

Jaded Burnout fucked around with this message at 20:13 on Aug 31, 2014

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

This isn't strictly an answer to your question, but I'd do something like this:

code:

class Door < ActiveRecord::Base
   has_many :leases
   has_one :active_lease, ->{ merge Lease.active }, class_name: 'Lease'
 end

 class Lease < ActiveRecord::Base
   belongs_to :door
   scope :active, ->{ where("? between start and end", Time.now) }
 end

It's the responsibility of a lease to define what "active" means. And defining active_lease as a relation rather than a method lets you avoid the N+1 problem by includesing :active_lease in your initial Lease query and not fetch it for every individual lease.

i.e.
code:

Door.all.includes(:active_lease).each do |d|
  puts d.active_lease
end

would only have to make 2 queries.

good jovi fucked around with this message at 00:05 on Sep 1, 2014

xenilk
Apr 17, 2004

ERRYDAY I BE SPLIT-TONING! Honestly, its the only skill I got other than shooting the back of women and calling it "Editorial".
^^^^^^

holy poo poo. Thanks! I would have honestly never thought of a solution like this.

KoRMaK
Jul 31, 2012



How would I do automated testing for javascript? I need to verify that bootstrap is working right after an upgrade and do regression testing, so that means making sure things like modals open and respond to input correctly.

Is there a way to do this in ruby or rails via automated testing? I can understand checking inputs/outputs on models and controllers and even views, but javascript seem like a can of worms. How do you describe what is acceptable passing criteria? Looking around, it seems like there are some options but nothing that is an internet favorite. I've spotted cucumber and jasmine. Are either of these great options, and if not is there something else that is?

RobertKerans
Aug 25, 2006

There is a heppy lend
Fur, fur aw-a-a-ay.
Has anyone managed to get Sass source maps working with Rails (or just Sass 3.3+)? Turns out it's pretty critical for my current project, and I'm faced with this clusterfuck involving sprockets, rails-sprockets and rails-sass. Everyone on issue trackers who's managed to get it working seems to have done so almost accidentally by managing to add just the right accidental combination of gem versions. I can get 3.whatever into my test app, but hosed if sprockets or whatever doesn't decide to play funny buggers. Spent half a day yesterday methodically bundling various different combinations, adding and removing gems and forking and updating and I am royally loving sick. gently caress

Jaded Burnout
Jul 10, 2004


KoRMaK posted:

How would I do automated testing for javascript? I need to verify that bootstrap is working right after an upgrade and do regression testing, so that means making sure things like modals open and respond to input correctly.

Is there a way to do this in ruby or rails via automated testing? I can understand checking inputs/outputs on models and controllers and even views, but javascript seem like a can of worms. How do you describe what is acceptable passing criteria? Looking around, it seems like there are some options but nothing that is an internet favorite. I've spotted cucumber and jasmine. Are either of these great options, and if not is there something else that is?

Cucumber supports JS via Capybara but that's for a specific kind of testing, namely your main business-cares-about-this behaviour. You don't want to be using it for testing all your little edge cases.

Jasmine is a unit testing framework and lots of people use it. I've never found one I really get on with so I don't test my JS, but this makes me a Bad Person.

I'd recommend starting with a combination of cucumber and jasmine, if you have trouble with them at least you'll know what to look for in other frameworks.

Adbot
ADBOT LOVES YOU

Jaded Burnout
Jul 10, 2004


RobertKerans posted:

Has anyone managed to get Sass source maps working with Rails (or just Sass 3.3+)? Turns out it's pretty critical for my current project, and I'm faced with this clusterfuck involving sprockets, rails-sprockets and rails-sass. Everyone on issue trackers who's managed to get it working seems to have done so almost accidentally by managing to add just the right accidental combination of gem versions. I can get 3.whatever into my test app, but hosed if sprockets or whatever doesn't decide to play funny buggers. Spent half a day yesterday methodically bundling various different combinations, adding and removing gems and forking and updating and I am royally loving sick. gently caress

To quote someone dealing with this yesterday, "source maps are why we switched from the asset pipeline to grunt", so you're not the only one finding it difficult.

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