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
Obsurveyor
Jan 10, 2003

Pardot posted:

I don't think I've ever used a for loop in ruby. I'm trying to think of a time, and just can't.

I almost used a for loop the other day but the number of lines made me dig further into Array and I found delete_if. It felt weird using a for loop to begin with. I actually had to look up the syntax for it. That was enough to explore my options further.

Adbot
ADBOT LOVES YOU

Civil Twilight
Apr 2, 2011

Doc Hawkins posted:

For loops are training wheels for java babies.

Don't say that around Zed. :ssh:

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.

Pardot posted:

I don't think I've ever used a for loop in ruby. I'm trying to think of a time, and just can't.

Hell, I didn't even use them at my last job, where I wrote C# all day. Or in Javascript for that matter.

kitten smoothie
Dec 29, 2001

A MIRACLE posted:

Nothing that most of the people (including myself) in this thread aren't already following as far as I can tell. But I did learn that `for loops` don't introduce a new scope for their iterators!
I think everyone in my office had a "today I learned" moment from that. Not that any one of us has could recall having used a for loop in Ruby, but that's neither here nor there.

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.
Zed is right though. I'd like to use for loops instead of #each in most cases, but I don't because of the scoping issue.

That said, block parameters didn't get a new scope in 1.8 either.

double sulk
Jul 2, 2010

Obsurveyor posted:

I almost used a for loop the other day but the number of lines made me dig further into Array and I found delete_if. It felt weird using a for loop to begin with. I actually had to look up the syntax for it. That was enough to explore my options further.

I literally wondered earlier today whether Ruby even had for loops and had to check as well, and I've been using it/Rails on and off in a more serious manner for a couple months now. I never see them used.

The each syntax is probably my favorite thing about Ruby.

Obsurveyor
Jan 10, 2003

Smol posted:

Zed is right though. I'd like to use for loops instead of #each in most cases, but I don't because of the scoping issue.

I disagree that he's right. for loops have a lot more problems than just line count. Blocks should be front and center in any teaching curriculum of ruby. He's bringing his own baggage(or you could say mores) from other languages and trying to shape ruby into that. This is bad and a disservice to his students.

I'll just leave it to Giles Bowkett:

Giles Bowkett posted:

Zed Shaw [...] he is in my personal opinion a maniac

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.

Zed is a bit off-kilter at times but for the most part gives good advice (if a bit expletive-laden). But as a noob susceptible to off-by-one errors, I'm more than happy to eschew for-loops in favor of iterators.

A MIRACLE fucked around with this message at 15:56 on Dec 13, 2012

Civil Twilight
Apr 2, 2011

A MIRACLE posted:

Zed is a bit off-kilter at times but for the most part gives good advice (if a bit expletive-laden). But as a noob susceptible to off-by-one errors, I'm more than happy to eschew for-loops in favor of iterators.

It's worth noting that the for-loop Zed is talking about is not an index-counting one, it's an iterator like #each.

Ruby code:
for item in an_array do
  item.something
end
Same as
Ruby code:
an_array.each {|item| item.something }
except for the scoping issue.

edit: (I either didn't realize, or forgot, that Ruby had this for-loop until github's style guide reminded me just recently, and I've been using Ruby on and off since version 1.4)

Civil Twilight fucked around with this message at 16:41 on Dec 13, 2012

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.
Procs and blocks are a great tool, but sometimes you just want to iterate over a collection. There is no need to make it more complicated than it has to be. For loop also reads better and is easier to type. #each is the right tool when you want to do a side-effect after a series of transformations.
Ruby code:
(1 .. 10).map { |i| i ** 2 }.select(&:even?).each { |i| puts i }
I think it's a shame that the scope for for loop variables wasn't changed for 2.0, but I understand the rationale.

Btw, "do" is optional on for loops when the loop spans multiple lines.

Smol fucked around with this message at 17:24 on Dec 13, 2012

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Civil Twilight posted:

It's worth noting that the for-loop Zed is talking about is not an index-counting one, it's an iterator like #each.

Ruby code:
for item in an_array do
  item.something
end

I've heard that this way is (or was) preferred at 37signals, and was even in Rails until 2010: https://github.com/rails/rails/comm.../index.html.erb

Lexicon
Jul 29, 2003

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

Smol posted:

There is no need to make it more complicated than it has to be. For loop also reads better and is easier to type. #each is the right tool when you want to do a side-effect after a series of transformations.

Your entitled to your opinion, but you are at odds with virtually the entire ruby community. each {} is the standard way to iterate over a collection, and for-loops look downright bizarre in ruby code. I've never even written one.

prom candy
Dec 16, 2005

Only I may dance

Cocoa Crispies posted:

I've heard that this way is (or was) preferred at 37signals, and was even in Rails until 2010: https://github.com/rails/rails/comm.../index.html.erb

Early Rails tutorials were all written like this and I believe the original scaffolds used for loops as well.

Lexicon
Jul 29, 2003

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

Lexicon posted:

Your entitled to your opinion, but you are at odds with virtually the entire ruby community. each {} is the standard way to iterate over a collection, and for-loops look downright bizarre in ruby code. I've never even written one.

Ok, I have far less conviction in this statement if DHH is a for-loop guy...

Bodybuilding Virgin 420
Aug 29, 2000

I think you're increasing complexity by using for loops. You'll still be writing each and writing it the "each way" with a block when you need to use each_with_index, each_slice, etc.

Also people should follow community style standards when more than 1 person is working on the code base. Like why have 2 spaces in ruby code instead of tabs? With tabs each person can set how much white space they like to see, wouldn't that be better? The problem is if people don't follow standards then code bases start becoming a mix of different styles and that decreases readability.

Doc Hawkins
Jun 15, 2010

Dashing? But I'm not even moving!



As with almost any programming language construct, you don't have to learn everything about how .each works to use it effectively.

The Sweetling
May 13, 2005

BOOMSHAKALAKA
Fun Shoe
Here're some easy noobish questions:

1. What's the proper way to safely load records and handle cases where nothing is retrieved, to avoid null pointers in the views? Blocks of if/else or unless aren't ideal.
2. Additionally, how can I reduce the amount of variables for the different types of records being retrieved? For example, I have a Goal model with a scope on a :daily boolean. Does it make sense to pull all daily records into a @daily_goals variable in the controller's load method or is there a better way?

Here's my controller:

code:
class GoalsController < ApplicationController
	include GoalsHelper
	before_filter :load

	def load
		@goal = Goal.new
		@all_goals = Goal.all
		@daily_goals = Goal.daily
		@todays_goals = Goal.today
		@all_completed_goals = Goal.complete

		@completed_daily_goals = @daily_goals.where(:complete=>true)
		@completed_todays_goals = @todays_goals.where(:complete=>true)

		unless !@daily_goals.nil? 
			@daily_goals = Array.new
		end

		unless !@todays_goals.nil? 
			@todays_goals = Array.new
		end

		unless !@all_completed_goals.nil? 
			@all_completed_goals = Array.new
		end

		unless !@all_goals.nil? 
			@all_goals = Array.new
		end
	end

	...blah blah...

Kallikrates
Jul 7, 2002
Pro Lurker
Some issues I see with your code separate from your 'nil pointer' issue
First off, you are calling Goal.all, and then calling several scopes on Goal (hint one of these is probably a subset of the other.) these all represent queries on your DB.

Without qualifying your before_filter it will run before every action on that controller considering what :load does this is not good.

Unless !@daily_goals.nil? tells me you don't understand unless. (it should be if @daily_goals.nil? or empy?).

Your scopes should return empty arrays not nil.

Without going into more of your code it's hard to tell how to fix or suggest a better alternative.

Kallikrates fucked around with this message at 16:54 on Dec 14, 2012

raej
Sep 25, 2003

"Being drunk is the worst feeling of all. Except for all those other feelings."
Any advanced will_paginate users out there?

For my collection, in the controller, I get all the beers for a user and retrieve beers belonging to users. This gets rendered with a view and a partial as follows:

Controller
Ruby code:
def cellar
    @user = User.find(params[:id])
    @title = @user.name + "\'s Cellar"
    @beers = @user.beers.group('name').paginate(page: params[:page]).order('created_at DESC')
    render 'show_cellar'
  end
Show_cellar
Ruby code:
 <% if @beers.any? %>
      <table class="beers">
        <th>Rating</th><th>Name</th><th>Brewery</th><th>ABV</th><th>Style</th><th>Amt</th>
        <%= render @beers %>
      </table>
      <%= will_paginate %>
    <% end %>
beers partial
Ruby code:
<tr>
  <td>
  	<div class="rating">
  	  <h4>4.5</h4>Rating
  	</div>
  </td>
  <td>
  	<h5><%= link_to beer.name, beer %></h5>
  </td>
  <td>
  	<%= link_to beer.brewery.name, beer.brewery %>
  </td>
  <td>
  	<%= beer.abv %>%
  </td>
  <td>
  	<%= beer.style %>
  </td>
  <td>
  	<%= @beers.count %>
  </td>
</tr>
The problem I'm getting is that the @beers.count comes back with an array of things, instead of the count for that beer and I see something like this:

{"Awesome Beer 1"=>10, "Awesome Beer 2"=>1, "Awesome Beer 3"=>1, "Awesome Beer 4"=>15}

When all I want is to get the count for that row of beer. What am I doing wrong here?

EDIT:
So the more I think about it, the more I'm thinking this isn't a paginate thing.

The logic should be as follows:

user -> cellared_beer <- beer

A user has many beers through cellared_beer.

A user can cellar more than one of the same beer.

I can display all of a user's beers with user.beers.

I want to be able to aggregate duplicate beers.

Use Case:
User adds beer 1.
User adds beer 1.
User adds beer 2.
User goes to cellar and sees:
Beer 1 - qty 2
Beer 1 - qty 1

raej fucked around with this message at 22:07 on Dec 14, 2012

The Sweetling
May 13, 2005

BOOMSHAKALAKA
Fun Shoe

Kallikrates posted:

Some issues I see with your code separate from your 'nil pointer' issue
First off, you are calling Goal.all, and then calling several scopes on Goal (hint one of these is probably a subset of the other.) these all represent queries on your DB.

Without qualifying your before_filter it will run before every action on that controller considering what :load does this is not good.

Unless !@daily_goals.nil? tells me you don't understand unless. (it should be if @daily_goals.nil? or empy?).

Your scopes should return empty arrays not nil.

Without going into more of your code it's hard to tell how to fix or suggest a better alternative.

Thanks for the tips homes, I rewrote my models and relationships.

raej
Sep 25, 2003

"Being drunk is the worst feeling of all. Except for all those other feelings."
I can simplify my problem a bit more after hammering at it a bit:

A user has many beers through cellared_beers
a beer has many users through cellared_beers

Because of this relationship, rails allows the command @user.beers to get a list of all beers cellared by a particular user.

Since a user can cellar more than one of the same beers, I want to scrunch those into the same row.

In SQL, I can accomplish this by:
code:
sqlite> select beers.name, beers.style, beers.abv, count(*)
...> from beers, cellared_beers
...> where beers.id = cellared_beers.beer_id
...> and cellared_beers.user_id = 1
...> group by beers.id;
Awesome Beer 1-10|IPA|10.0|10
Awesome Beer 1-11|IPA|11.0|1
Awesome Beer 1-13|IPA|13.0|1
Awesome Beer 1-16|IPA|16.0|15

Big Nubbins
Jun 1, 2004
Is there a way to set the version of SSL used when you set "config.force_ssl" to true in Rails 3.2? I'm forcing SSL in my configuration and having an issue with requests to our payment gateway timing out. For what it's worth, we're using ActiveMerchant.

We managed to reproduce the issue in the following script:
code:
#! /usr/bin/env ruby
require 'net/https'
require 'uri'

uri = URI.parse(ARGV[0] || 'https://secure.networkmerchants.com/gateway/transact.dll')
http = Net::HTTP.new(uri.host, uri.port)
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.use_ssl = true if uri.scheme == "https"  # enable SSL/TLS
http.ssl_version = :SSLv3
http.start {
  http.request_get(uri.path) { |res|
    print res.body
  }
}
Commenting out the "http.ssl_version = :SSLv3" line causes the request to time out.

Edit: Never mind, I found out that I can simply monkey-patch the SSL version into ActiveMerchant::Connection's "configure_ssl" method.

Big Nubbins fucked around with this message at 17:38 on Dec 20, 2012

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.
Hope you're not using OpenSSL::SSL::VERIFY_NONE in the real app.

Edit: VVV Yeah, just wanted to make sure. There's a lot of crappy copy-paste code like that lying around.

Smol fucked around with this message at 01:10 on Dec 22, 2012

Big Nubbins
Jun 1, 2004

Smol posted:

Hope you're not using OpenSSL::SSL::VERIFY_NONE in the real app.

God no, that was just a sample script set up for testing. I ended up fixing it by forking ActiveUtils (ActiveMerchant dependency) and setting the SSL version in the same place it's setting the rest of the SSL options.

thegasman2000
Feb 12, 2005
Update my TFLC log? BOLLOCKS!
/
:backtowork:
I am interested in learning some RoR and noticed Ruby is offered on Code Academy. Whats the consensus on learning Ruby through there and its helpfulness for RoR?

noskill
Dec 6, 2012

OMCK

thegasman2000 posted:

I am interested in learning some RoR and noticed Ruby is offered on Code Academy. Whats the consensus on learning Ruby through there and its helpfulness for RoR?

The short answer is that it depends on your previous programming background.

I personally used a bunch of Programming Ruby from PragProg, O'Reilly books and Peep Code screencasts to get the basics straight (keep in mind that you probably want to learn Ruby 1.9 now while most old books were focused on 1.8 even though differences aren't huge unless you're getting in all the gritty details).

You could start with Code Academy and see if that works for you and you "get" it. Worst case scenario is that it doesn't and you don't like it -- and then you could try something different.

There's no one true way to learn something anyway.

Siguy
Sep 15, 2010

10.0 10.0 10.0 10.0 10.0
Amateur opinion, but I personally have found that those sites work a lot better if you already have a little bit of knowledge.

I'd suggest working through a few other tutorials and getting a rough knowledge of how things work and then going through Code Academy or Code School. You don't need to be an expert just to take a course, but it helps if everything isn't completely new to you.

Lexicon
Jul 29, 2003

I had a beer with Stephen Harper once and now I like him.
What's preferable?

a = Hash.new or a = {}

I'm a python refugee and am biased towards the latter, but I see both. Is there a majority opinion on this?

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.
The latter. Only use Hash.new when you need to use one of the special constructors for providing default values or something similar.

The same applies for Arrays as well.

Lexicon
Jul 29, 2003

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

Smol posted:

The latter. Only use Hash.new when you need to use one of the special constructors for providing default values or something similar.

The same applies for Arrays as well.

Great, thanks. Every time I create one, I wonder which to use. This finally can be put to rest.

Civil Twilight
Apr 2, 2011

For the record:
Ruby code:
require 'benchmark'
n = 10_000_000
Benchmark.bm(8) do |b|
  b.report("{}")       { n.times { h = {} }}
  b.report("Hash.new") { n.times { h = Hash.new }}
end
code:
% ruby hash_bench.rb
               user     system      total        real
{}         1.180000   0.000000   1.180000 (  1.179753)
Hash.new   6.310000   0.030000   6.340000 (  6.343849)
I don't know if it makes any difference memory usage.

Daynab
Aug 5, 2008

Hi, I'm interested in learning Ruby and then RoR but I had a question and there's no general Ruby thread - how useful is plain standalone Ruby to code programs compared to say... Python? Is it versatile or is it more "the language that Rails just happens to run on"?

noskill
Dec 6, 2012

OMCK

Daynab posted:

Hi, I'm interested in learning Ruby and then RoR but I had a question and there's no general Ruby thread - how useful is plain standalone Ruby to code programs compared to say... Python? Is it versatile or is it more "the language that Rails just happens to run on"?

I use Ruby as general scripting language all the time. Pretty much everything that helps me in solving certain problem. Grab a bunch of HTML pages and do something with them? No problem, I can do that in Ruby. Parse CSV files, do some calculations with them and save results? No problem, I can do that in Ruby. Call some external services and save responses in SQLite? No problem, I can do that in Ruby.

Granted, Ruby is not all-powerful and there are certain things that you won't be able to do (or, rather, won't be able to do as easily) but those are very specific things. And you'll probably have to use some gems to make your life easier. But as a general scripting language, I find it to be tremendously helpful.

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.

Civil Twilight posted:

For the record:
Ruby code:
require 'benchmark'
n = 10_000_000
Benchmark.bm(8) do |b|
  b.report("{}")       { n.times { h = {} }}
  b.report("Hash.new") { n.times { h = Hash.new }}
end
code:
% ruby hash_bench.rb
               user     system      total        real
{}         1.180000   0.000000   1.180000 (  1.179753)
Hash.new   6.310000   0.030000   6.340000 (  6.343849)

I don't know if it makes any difference memory usage.
I think a fairer benchmark would be {} vs Hash[]. Although I suspect that {} will win even in that case (no need to look up the constant Hash, for example).

E: Spelling

Smol fucked around with this message at 15:24 on Dec 24, 2012

Civil Twilight
Apr 2, 2011

Smol posted:

I think a fairer benchmark would be {} vs Hash[]. Although even then I suspect that {} will win even in that case (no need to look up the constant Hash, for example).

It wasn't about fairness; Lexicon asked about Hash.new. Since you brought it up, though:
code:
               user     system      total        real
{}         1.170000   0.000000   1.170000 (  1.175680)
Hash[]     1.650000   0.000000   1.650000 (  1.649403)

Lexicon
Jul 29, 2003

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

Daynab posted:

Hi, I'm interested in learning Ruby and then RoR but I had a question and there's no general Ruby thread - how useful is plain standalone Ruby to code programs compared to say... Python? Is it versatile or is it more "the language that Rails just happens to run on"?

As a data point, I used Ruby extensively for scripting, parsing, automation etc long before I ever got into rails.

Civil Twilight
Apr 2, 2011

Lexicon posted:

As a data point, I used Ruby extensively for scripting, parsing, automation etc long before I ever got into rails.

I've used Ruby for years, and never actually done any production Rails programming. :ssh:

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I am one of those programmers who has put off getting into a proper testing regimen. I can write a test sometimes, I find it more complicated than it needs to be. Every company is running 16 different testing gems at the same time due to every programmer having their preference for fancy ways of doing the exact same thing, rspec, cucumber, etc. and I have to dig into them. But I don't like doing it.

I'd like to get myself educated on testing and finding simple tools that do the job without a bunch guffaw about it. Rails 4 and minitest seems to be the ticket. I'm having a hard time finding a good document that takes me through getting started. I understand the general idea, I understand TDD workflow, I want a starters or beginners guide to testing that doesn't get all tippy-toed smiley faced about the latest testing fad.

Any suggestions would be helpful.

Obsurveyor
Jan 10, 2003

Nolgthorn posted:

I'd like to get myself educated on testing and finding simple tools that do the job without a bunch guffaw about it. Rails 4 and minitest seems to be the ticket. I'm having a hard time finding a good document that takes me through getting started. I understand the general idea, I understand TDD workflow, I want a starters or beginners guide to testing that doesn't get all tippy-toed smiley faced about the latest testing fad.

http://ruby.railstutorial.org/ruby-on-rails-tutorial-book

Adbot
ADBOT LOVES YOU

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Thanks. I was looking around for an answer to my question above and I found this link very helpful. http://blog.arvidandersson.se/2012/03/28/minimalicous-testing-in-ruby-1-9

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