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
hmm yes
Dec 2, 2000
College Slice
At least it was an easy fix? :)

Adbot
ADBOT LOVES YOU

Steve French
Sep 8, 2003

This isn't rails, just vanilla ruby (1.9.2p180 on ubuntu ec2), but this seems like the best place to ask on here.

I've got some code that hangs under certain circumstances (most of the time it's fine, so unfortunately this isn't easily repeatable by others).

This is the bit in question:

code:
  def self.sys(env, *command)
    IO.pipe do |rd, wr|
      read_thread = Thread.start { rd.read }
 
      result = system(env, *command, err: wr, out: wr, close_others: true)
      wr.close
 
      raise "error: #{command * ' '}\n#{read_thread.value}" unless $?.success?
 
      result
    end
  end
(yes I know there are other simpler ways of doing this, I didn't write this code, I'm just trying to understand why it is behaving this way)

What I'm observing is a hang on read_thread.value; it just blocks forever waiting on the read thread. Immediate suspicion with this sort of code is usually that the write half of the pipe hasn't been closed, except that in this case it has (as is clear by inspection of the code, also verified with lsof: the process has only one FIFO open.

Does anyone have any clues what might be causing this to hang? (Or have any brilliant debugging tips?)

DankTamagachi
Jan 20, 2005
Tamagachi to your throat!
I'm trying to debug a strange issue with rails forms helpers I haven't encountered before. I posted on stackoverflow so instead of re-typing the whole thing here, I'll provide a link.

Anybody see this before? For some reason, the text_field helper in rails is providing values in the POST params as an array instead of as a pure string value.

http://stackoverflow.com/q/15262119/1268161

E: Welp, somebody got it. Dumb mistake. I was supposed to use text_field_tag instead of text_field.

DankTamagachi fucked around with this message at 04:06 on Mar 7, 2013

The Journey Fraternity
Nov 25, 2003



I found this on the ground!
*edit* I'm a moron

het
Nov 14, 2002

A dark black past
is my most valued
possession

Steve French posted:

Does anyone have any clues what might be causing this to hang? (Or have any brilliant debugging tips?)
What does strace say the executed command is doing while hanging? Just attaching to the running process may not produce anything useful, but you could prepend the strace to the command you execute and have it output to a temp file that you remove on success.

One thought I had was that maybe it's a buffered I/O thing (probably on the command you're executing), but that seems kind of weird/unlikely for it to hang very long

Steve French
Sep 8, 2003

het posted:

What does strace say the executed command is doing while hanging? Just attaching to the running process may not produce anything useful, but you could prepend the strace to the command you execute and have it output to a temp file that you remove on success.

One thought I had was that maybe it's a buffered I/O thing (probably on the command you're executing), but that seems kind of weird/unlikely for it to hang very long

The executed command has already completed; it failed (in this particular case, as expected). The fact that it has completed and failed is what it is causing the call to read_thread.value, which is what is hanging.

KoRMaK
Jul 31, 2012



I have three questions:

1) I want to put a :limit clause on a relationship using a variable from the same class, like this (but it doesn't work).
Ruby code:
class Account < ActiveRecord::Base
  has_many :things, :limit => self.things_limit
end
2) How would I override a relationship so that I can add in my own customizations
Ruby code:
class Account < ActiveRecord::Base
  has_many :things

  def things
    things.limit(5) #use the original things relationship and limit the return count, for example
  end
end
3) How would I override a model's find or all commands to only return the first X count of records (Thing is a model)
Ruby code:
Thing.all #would return only the first X count of records

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.

KoRMaK posted:

1) I want to put a :limit clause on a relationship using a variable from the same class, like this (but it doesn't work).

is `things_limit` a class method or an instance method? I think this might only work with class methods.

KoRMaK posted:

2) How would I override a relationship so that I can add in my own customizations

Look at the options for this in the documentation. You might have to :extend the association.
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

KoRMaK posted:

3) How would I override a model's find or all commands to only return the first X count of records (Thing is a model)
Ruby code:
Thing.all #would return only the first X count of records

try something like

Ruby code:
class MyModel < ActiveRecord::Base
  def self.all
    super().limit(X)
  end
end
http://guides.rubyonrails.org/active_record_querying.html#limit-and-offset

UxP
Aug 27, 2007

A MIRACLE posted:

is `things_limit` a class method or an instance method? I think this might only work with class methods.


Look at the options for this in the documentation. You might have to :extend the association.
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html


try something like

Ruby code:
class MyModel < ActiveRecord::Base
  def self.all
    super().limit(X)
  end
end
http://guides.rubyonrails.org/active_record_querying.html#limit-and-offset

That won't quite work.
code:
NoMethodError: undefined method `limit' for #<Array:0x007fbde68235b0>
this will though
Ruby code:
class MyModel < ActiveRecord::Base
  def self.all
    super(:limit => 5)
  end
end
And a more idiomatic way which preserves compatibility:
Ruby code:
class MyModel < ActiveRecord::Base
  def self.all(opts={})
    super({:limit => 5}.merge(opts))
  end
end
That allows `MyModel.all` to return 5, but `MyModel.all(:limit => 100)` returns 100.

KoRMaK
Jul 31, 2012



A MIRACLE posted:

is `things_limit` a class method or an instance method? I think this might only work with class methods.
I have a confession: I still don't know how to tell the difference between the two after 1yr+ RoR development :eng99: things_limit is a column on the Account model.

I'm still taking in and processing the other couple of comments from you guys, thanks for the replies.

noskill
Dec 6, 2012

OMCK

KoRMaK posted:

I have a confession: I still don't know how to tell the difference between the two after 1yr+ RoR development :eng99: things_limit is a column on the Account model.

Fortunately that is easy:
code:
class Something
  def self.method_one
    # class method
  end

  def method_two
    # instance method
  end
end
Then you can invoke them like this:
code:
Something.method_one # works
Something.method_two # fails with "no method error"

Something.new.method_one # fails with "no method error"
Something.new.method_two # works

Lexicon
Jul 29, 2003

I had a beer with Stephen Harper once and now I like him.
^ The use of self for that has always bugged me about ruby. I don't think they could have chosen a worse keyword to use in that position - its connotation is inextricably tied to "instance" not "class". Especially to a python refugee...

That's one of the only things I'd change about ruby if somehow my opinion mattered on future direction :)

manero
Jan 30, 2006

Lexicon posted:

^ The use of self for that has always bugged me about ruby. I don't think they could have chosen a worse keyword to use in that position - its connotation is inextricably tied to "instance" not "class". Especially to a python refugee...

That's one of the only things I'd change about ruby if somehow my opinion mattered on future direction :)

Well, you could do it like this:

code:
class Something
  def Something.method_one
  end
end
But then it's a pain in the butt to change. You can also do:

code:
class Something
  class << self
    def method_one
    end
  end
end
Which isn't all that much more apparent.

kitten smoothie
Dec 29, 2001

Is Railsconf worth the money? Google I/O registration failed me this year and so now I'm trying to decide if I should burn the money on Railsconf instead.

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.

I decided not to go because work won't pay for it and it's on the other coast :-(. So I'm going on a month-long vacation to Asia instead! :rolleye:

Lexicon
Jul 29, 2003

I had a beer with Stephen Harper once and now I like him.

manero posted:

Well, you could do it like this:

Cool. I didn't know about the former syntax, actually. I guess it doesn't really matter that alternatives exist as you can't reasonably use them and not be out-of-lockstep with the rest of the ruby community - I'm mostly just annoyed by what they chose for the default. When I first learned that, I was like "Wait, what? 'self' means 'class' method?? COME ON!"

Novo
May 13, 2003

Stercorem pro cerebro habes
Soiled Meat

kitten smoothie posted:

Is Railsconf worth the money? Google I/O registration failed me this year and so now I'm trying to decide if I should burn the money on Railsconf instead.

I find that I can get as much or more out of watching videos of conference talks after the fact without flying across the country to sit in a room where everyone is dicking around on their laptops. I've been told that this means I don't "get" conferences though, so YMMV.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I've got a Cool question for ActiveRecord peeps.

Take a look.

Activerecord exposes a very helpful .build method on associations.
Ruby code:
# In associated model
def build_a_thing(name)
  things.build(name: name)
end

def another_way_to_build_a_thing(name)
  build_thing(name: name)
end
A useful but separate thing you can do is essentially define a scope using a class method.
Ruby code:
# class Thing
scope :recent, -> { order(created_at: :desc) }

def self.only_nils
  where(name: nil)
end

Thing.recent.only_nils
ActiveRecord appears to have no understanding about what I am trying to do when I combine them.
Ruby code:
# class Thing
def self.find_or_build_from_full_name(full_name)
  name = full_name.split(' ').first
  find_by(name: name) || build(name: name)
end
It breaks on build.

quote:

Undefined method 'build' for Class.

So if I can do:
Ruby code:
# class Thing
def self.find_from_full_name(full_name)
  name = full_name.split(' ').first
  find_by(name: name)
end

things.find_from_full_name(full_name)
In place of:
Ruby code:
# In associated model
name = full_name.split(' ').first
things.find_by(name: name)
Why can't I do:
Ruby code:
# class Thing
def self.build_from_full_name(full_name)
  name = full_name.split(' ').first
  build(name: name)
end

things.build_from_full_name(full_name)
In place of:
Ruby code:
# In associated model
name = full_name.split(' ').first
things.build(name: name)
?

Or even better, how would I do this.

Doc Hawkins
Jun 15, 2010

Dashing? But I'm not even moving!


Build is a method on associations, not on models. It basically calls `Thing.new(thing_haver: thing_haver_instance_on_whose_things_association_we_called_build)`.

You might prefer an instance method on the class which holds the association.

Ruby code:
class ThingHaver
  has_many :things

  def build_named_thing(full_name)
    name = full_name.split(' ').first
    things.find_or_initialize_by_name(name)
  end
end

Doc Hawkins fucked around with this message at 16:30 on Mar 14, 2013

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Yeah.

My confusion comes from associations and classes both having find_by but not both having build and therefore it strictly not being available. In my example should I assume the find_by isn't doing what I want in this instance:

Ruby code:
# class Thing
scope :no_cats, -> { where(cats_count: 0) }

def self.find_from_full_name(full_name)
  name = full_name.split(' ').first
  find_by(name: name)
end

# 1
Thing.no_cats.find_from_full_name(full_name)

# 2
name = full_name.split(' ').first
Thing.no_cats.find_by(name: name)
Will #1 return a record that has cats and #2 will not, do they both behave the same?

Nolgthorn fucked around with this message at 17:00 on Mar 14, 2013

Doc Hawkins
Jun 15, 2010

Dashing? But I'm not even moving!


Well, there is no method `find_by` in rails, though there are the dynamic finders `find_by_*` for each attribute an AR model has, and `find_by_attributes` which would work with arguments like `(name: name_variable)`.

I'm actually not sure if those methods return chainable scopes (probably?), but `where` definitely does, and you can use it to write class methods that can chain, be chained upon, and be called on associations.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Novo posted:

I find that I can get as much or more out of watching videos of conference talks after the fact without flying across the country to sit in a room where everyone is dicking around on their laptops. I've been told that this means I don't "get" conferences though, so YMMV.

I went in 2011 and just did the free hallway track, and felt like I got my money's worth. Go for the inspiration and the networking, and consider that it's a great way to get work to pay for you to talk to the zillion companies there that will be begging for new employees.

(Looks like they didn't accept my talk :( )

turn it up TURN ME ON
Mar 19, 2012

In the Grim Darkness of the Future, there is only war.

...and delicious ice cream.
I'm learning Ruby right now, going through the Koans and I'm trying to create a method for one of the exercises. Right now, though, I'm stuck on trying to match up a set of numbers to an array.

Bottom line: Does .include? work if you pass an array to it? Will it then look inside a given array to see if the things are in there?

Basically, here's what I have now:

code:

def score(dice)
    if dice.empty?
      score = 0
    elsif dice.include?([1,1,1]) && dice.length == 3
      score = 1000
    end
end

What is being passed through is score([1,1,1]) and it is appearing to return nil. Am I asking to include a sub-array by using [1,1,1]? Sorry for the newbie question here.

Soup in a Bag
Dec 4, 2009

SquadronROE posted:

I'm learning Ruby right now, going through the Koans and I'm trying to create a method for one of the exercises. Right now, though, I'm stuck on trying to match up a set of numbers to an array.

Bottom line: Does .include? work if you pass an array to it? Will it then look inside a given array to see if the things are in there?

Nope. It will look for the object it's passed (in this case the entire array) and that's it.

Ruby code:
> [1, 1, 1, 1].include?([1, 1, 1])
=> false

> [[1, 1, 1], 1].include?([1, 1, 1])
=> true
The online Ruby docs are pretty handy for these sorts of questions.

Lexicon
Jul 29, 2003

I had a beer with Stephen Harper once and now I like him.

Learn to love the console (irb in your terminal app) as Soup in a Bag just did. Any time you are unsure, you can simply run the command to see what happens and experiment to your heart's content.

This accounts for a massive, massive difference in programmer productivity in ruby for those who came from the Java, C++, etc worlds. Big hulking slow tools, edit-compile-run cycles, etc.

turn it up TURN ME ON
Mar 19, 2012

In the Grim Darkness of the Future, there is only war.

...and delicious ice cream.
Ah, very very cool. That is about a billion times easier than I thought it would be. Thanks.

EDIT: And thanks to IRB I was able to figure out that I needed dice.count(1) == 3. Man, that is SO much easier. Also, I did actually check out the ruby docs before I asked, but didn't make the connection between it looking for a literal array rather than what was considered in the array.

turn it up TURN ME ON fucked around with this message at 23:48 on Mar 15, 2013

Hefty
Jun 11, 2008

Speaking of IRB, I just found out about Pry. Even though I only know how to use the basic features (new to Ruby as well), it looks pretty awesome. Check out the intro screencast http://pryrepl.org/.

Civil Twilight
Apr 2, 2011

Pry's edit-method by itself is reason enough for me to use it over irb.

manero
Jan 30, 2006

Hefty posted:

Speaking of IRB, I just found out about Pry. Even though I only know how to use the basic features (new to Ruby as well), it looks pretty awesome. Check out the intro screencast http://pryrepl.org/.

Pry is awesome, as is awesome_print

MrDoDo
Jun 27, 2004

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

Hefty posted:

Speaking of IRB, I just found out about Pry. Even though I only know how to use the basic features (new to Ruby as well), it looks pretty awesome. Check out the intro screencast http://pryrepl.org/.


Both of these are awesome, thanks for the heads up.

DONT THREAD ON ME
Oct 1, 2002

by Nyc_Tattoo
Floss Finder
beep boop

https://groups.google.com/forum/?fromgroups#!topic/rubyonrails-security/4_QHo4BqnN8

https://groups.google.com/forum/?fromgroups#!topic/rubyonrails-security/KZwsQbYsOiI

https://groups.google.com/forum/?fromgroups#!topic/rubyonrails-security/zAAU7vGTPvI

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.
Well, it is Monday, all right.

Lexicon
Jul 29, 2003

I had a beer with Stephen Harper once and now I like him.

I set up a rake task for bundle audit and it's unfortunately not flagging any of these in its output. Anyone know why?

DONT THREAD ON ME
Oct 1, 2002

by Nyc_Tattoo
Floss Finder
Probably because the post is an hour old and audit isn't aware of it yet

Lexicon
Jul 29, 2003

I had a beer with Stephen Harper once and now I like him.

chumpchous posted:

Probably because the post is an hour old and audit isn't aware of it yet

I should've read more before posting. Turns out a feature of it is that it doesn't require a network connection, and has its own dataset of vulnerabilities that gets updated periodically. So presumably you only ever get notified if you bundle update it, and then run it? Hmph.

DONT THREAD ON ME
Oct 1, 2002

by Nyc_Tattoo
Floss Finder

Lexicon posted:

I should've read more before posting. Turns out a feature of it is that it doesn't require a network connection, and has its own dataset of vulnerabilities that gets updated periodically. So presumably you only ever get notified if you bundle update it, and then run it? Hmph.

wow, I also assumed it was querying a server somewhere. It would make sense that it takes at least an hour or two to get updates. That kinda sucks, but I don't think it's really intended as an up to the minute security watchdog; it's more more of a thing to use before an initial rollout/after major updates.

Lexicon
Jul 29, 2003

I had a beer with Stephen Harper once and now I like him.

chumpchous posted:

wow, I also assumed it was querying a server somewhere. It would make sense that it takes at least an hour or two to get updates. That kinda sucks. I don't think it's really intended as an update to the minute security watchdog, and more of a thing to make sure something old doesn't get past you.

Yeah :/ Fair enough - still a useful thing, but I guess it's not quite what I thought it was.

edit: I totally don't blame anyone for not wanting to run a server for free, but it's rather humorous in 2013 to call doesn't-rely-on-network a feature. You can get gently caress-all done without a network connection, including updating the drat vulnerability list.

Lexicon fucked around with this message at 19:36 on Mar 18, 2013

DONT THREAD ON ME
Oct 1, 2002

by Nyc_Tattoo
Floss Finder

Lexicon posted:

Yeah :/ Fair enough - still a useful thing, but I guess it's not quite what I thought it was.

edit: I totally don't blame anyone for not wanting to run a server for free, but it's rather humorous in 2013 to call doesn't-rely-on-network a feature. You can get gently caress-all done without a network connection, including updating the drat vulnerability list.

Yeah it would just need to be an RSS feed setup somewhere with a vulnerability list.

Anyhow, it's not going to tell you anything that the google group doesn't, so your best bet is to just subscribe to that.

Lexicon
Jul 29, 2003

I had a beer with Stephen Harper once and now I like him.
Why can't :until be used as a hash key?

Ruby code:
1.9.3p0 :003 >  {a: 1, b:2}.stringify_keys == {'a' => 1, 'b' => 2}
 => true 
1.9.3p0 :004 >  {a: 1, until: 2}.stringify_keys == {'a' => 1, 'until' => 2}
1.9.3p0 :005?>   # doesn't return from line
This seems insane to me.

Adbot
ADBOT LOVES YOU

Pardot
Jul 25, 2001




Lexicon posted:

Why can't :until be used as a hash key?

Ruby code:
1.9.3p0 :003 >  {a: 1, b:2}.stringify_keys == {'a' => 1, 'b' => 2}
 => true 
1.9.3p0 :004 >  {a: 1, until: 2}.stringify_keys == {'a' => 1, 'until' => 2}
1.9.3p0 :005?>   # doesn't return from line
This seems insane to me.

is stringify_keys some sort of rails thing?

Ruby code:
[1] pry(main)> RUBY_DESCRIPTION
=> "ruby 1.9.3p0 (2011-10-30 revision 33570) [x86_64-darwin11.2.0]"
[2] pry(main)> {a: 1, until: 2}.stringify_keys
NoMethodError: undefined method `stringify_keys' for {:a=>1, :until=>2}:Hash
from (pry):2:in `__pry__'
[3] pry(main)> {a: 1, until: 2}.to_a
=> [[:a, 1], [:until, 2]]
edit, works on my machine

Ruby code:
[4] pry(main)> require 'active_support/all'
=> true
[5] pry(main)> {a: 1, until: 2}.stringify_keys
=> {"a"=>1, "until"=>2}

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