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
Dooey
Jun 30, 2009
Son, I taught myself x86 assembly by reading disassembled executables. I'll manage. (Also I messed around in PHP for a bit and there is no way I'm going back to using that abomiation)

Adbot
ADBOT LOVES YOU

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

NotShadowStar posted:

Step away from Rails for a while. Rails assumes you are an expert already, so if you're not you're likely going to be very, very lost. Especially with all the crazy abstraction poo poo 3.1 is going to do.

From what I've seen, the model side of things isn't changing much, and it's still the best place (unless you need to use Concerns) to put your important business logic; reusable from queue workers or ActionMailer receivers, easy to unit test, and you can make raw objects to control processes that don't have a single-table data store (i.e. a HtmlSession model to encapsulate the authentication process for a web-browser consumer).

If you just remember that ActionController is a fancy DSL, views are literally a whole new language that runs inside the controller, and that models don't need to be ActiveRecord you'll do fine.

rugbert
Mar 26, 2003
yea, fuck you
I have a quick association question.

My image model is polymorphic so I can use it for 3 different things:
employee bios(has_one), client bios(has_one), and blog entries(has many)

I cant get the bios to work tho, whenever I try to upload an image I get unknown attribute errors.
code:
unknown attribute: file
Here are my models
code:
IMAGE
belongs_to :asset, :polymorphic => true, :autosave => true
has_attached_file :file, :styles => { blah blah blah}

ClientBio
has_one :image, :as => :asset, :dependent => :destroy
Can I only use polymorphic models with has_many?

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

rugbert posted:

I cant get the bios to work tho, whenever I try to upload an image I get unknown attribute errors.
code:
unknown attribute: file

Do you have the stack trace for this? Are you calling a_bio.file or a_bio.image.file ?

rugbert
Mar 26, 2003
yea, fuck you

BonzoESC posted:

Do you have the stack trace for this? Are you calling a_bio.file or a_bio.image.file ?

Heres the application trace
code:
ActiveRecord::UnknownAttributeError (unknown attribute: file):
  app/controllers/admin/client_bios_controller.rb:28:in `new'
  app/controllers/admin/client_bios_controller.rb:28:in `create'
And that line is : @client = ClientBio.new(params[:client_bio])

And here is my form
code:
<%= form_for [:admin,@client],:html =>{:multipart => true} do |f| %>
blah blah blah
<%= f.label "Profile Image" %>
<%= f.file_field :file %>
blah blah blah
The form works as long as I dont try to upload a file

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

rugbert posted:

Heres the application trace
code:
ActiveRecord::UnknownAttributeError (unknown attribute: file):
  app/controllers/admin/client_bios_controller.rb:28:in `new'
  app/controllers/admin/client_bios_controller.rb:28:in `create'
And that line is : @client = ClientBio.new(params[:client_bio])

And here is my form
code:
<%= form_for [:admin,@client],:html =>{:multipart => true} do |f| %>
blah blah blah
<%= f.label "Profile Image" %>
<%= f.file_field :file %>
blah blah blah
The form works as long as I dont try to upload a file

The file_field should be in a fields_for block, as per http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for . It's trying to set @client.file, and you want it going to @client.image.file.

rugbert
Mar 26, 2003
yea, fuck you
Ahhh gotcha, that worked. Now when Im try to view with:

code:
(this is outside the fields for form)

<li class="image_container">
  <%= image_tag(f.object.file.url(:thumb)) %>
</li>
I get the error: private method `file' called for #<ClientBio:0x00000003ede0b0>

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

rugbert posted:

Ahhh gotcha, that worked. Now when Im try to view with:

code:
(this is outside the fields for form)

<li class="image_container">
  <%= image_tag(f.object.file.url(:thumb)) %>
</li>
I get the error: private method `file' called for #<ClientBio:0x00000003ede0b0>

Because a ClientBio doesn't have a file method? Should you be calling f.object.image.file.url perhaps?

Three dots in an invocation is too many anyways, so you should probably wrap that in a method on whatever f is, and write tests for it to make sure there's a sane fallback if there's no clientbio, image, or file.

Cocoa Crispies fucked around with this message at 19:38 on Jun 3, 2011

rugbert
Mar 26, 2003
yea, fuck you

BonzoESC posted:

Because a ClientBio doesn't have a file method? Should you be calling f.object.image.file.url perhaps?

Three dots in an invocation is too many anyways, so you should probably wrap that in a method on whatever f is, and write tests for it to make sure there's a sane fallback if there's no clientbio, image, or file.

OH gotcha. Yea, I think that OOP class I took last semester just finally kicked in when I read that. Thanks!

On another note - is there a way to exclude a path from a route?

I have this route
code:
  match "/:section" => "index#section", :as => :section
Which takes in arguments to route uses to specific sections dynamically, but I need to make sure my blog namespace still works which it doesnt since the above route exists.

ah gently caress you know what, matching that route on just about fucks everything up. I was hoping to build a CMS where users could make their own site sections and poo poo but I dont see how thats going to work out now.

rugbert fucked around with this message at 03:43 on Jun 6, 2011

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

rugbert posted:

OH gotcha. Yea, I think that OOP class I took last semester just finally kicked in when I read that. Thanks!

On another note - is there a way to exclude a path from a route?

I have this route
code:
  match "/:section" => "index#section", :as => :section
Which takes in arguments to route uses to specific sections dynamically, but I need to make sure my blog namespace still works which it doesnt since the above route exists.

ah gently caress you know what, matching that route on just about fucks everything up. I was hoping to build a CMS where users could make their own site sections and poo poo but I dont see how thats going to work out now.

Did you read any of the comments in the routes.rb file?

rugbert
Mar 26, 2003
yea, fuck you

BonzoESC posted:

Did you read any of the comments in the routes.rb file?

I dont think it really helped, what I did find however was an old project I worked on with this company a few months back. Looks like I can loop through a model in my routes file and have routes created dynamically:
[code]
Section.all.each do |section|
match "/#{section.name}" => "index#section", :as => "#{section.name}"
[code/]

Pretty cool.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

rugbert posted:

I dont think it really helped, what I did find however was an old project I worked on with this company a few months back. Looks like I can loop through a model in my routes file and have routes created dynamically:
code:
  Section.all.each do |section|
    match "/#{section.name}" => "index#section", :as => "#{section.name}"


Pretty cool.
Please don't do that; you'll have to restart your app every time someone makes a new Section.

code:
  # The priority is based upon order of creation:
  # first created -> highest priority.

rugbert
Mar 26, 2003
yea, fuck you

BonzoESC posted:

Please don't do that; you'll have to restart your app every time someone makes a new Section.

code:
  # The priority is based upon order of creation:
  # first created -> highest priority.

Oh awesome, that makes everything and more a lot easier. Thanks!

On something else altogether. When I use group_by{blah blah blah} to group a query in my controller, does it produce an array of records? Im trying to paginate the groups and not the records but I cant seem to get it to work.

Bosnian!
Dec 22, 2008
Hi folks, I have a quick question that I am sure someone can tell me the answer to. Please bear with me, I am very very new to web programming and as such probably look pretty dumb with this. I have a web service that is producing a JSON file for me for a faculty directory mobile app I am creating using Ruby. My question is given the following format of my JSON output, how would I go about displaying each element on the page? Here is my exact JSON format:

{
class: "LNameResponse class is here"
- people: [
- {
+ class: "FacPerson class is here"
+ email: "personsemailishere"
+ firstName: "firstnameishere"
+ lastName: "lastnameishere"
+ phoneNumber: "phonenumberishere"
+ streetLine1: "address1ishere"
+ streetLine2: "address2ishere"
+ streetLine3: "address3ishere"
},
- {
+ class: "FacPerson class is here"
+ email: "personsemailishere"
+ firstName: "firstnameishere"
+ lastName: "lastnameishere"
+ phoneNumber: "phonenumberishere"
+ streetLine1: "address1ishere"
+ streetLine2: "address2ishere"
+ streetLine3: "address3ishere"
}
]
}

I am basically getting this back except add another 3-4 people in the people array. I can verify through my log file that the JSON is being returned from the web service and the values are correct. What I would like is to display this information in my view for each person in the people array one at a time. I know how to loop through and do this but everytime I try to access the people array I get a nil:nilclass error. Not sure what to do, any help would be appreciated.

And sorry if this just sounds like sheer and complete jibberish, I am not too good at explaining problems sometimes.

revmoo
May 25, 2006

#basta
I need to learn Rails in a month, coming from a PHP background. What is the best book to buy?

Obsurveyor
Jan 10, 2003

revmoo posted:

I need to learn Rails in a month, coming from a PHP background. What is the best book to buy?
Going from PHP to Rails a few months ago, I thought the Rails Tutorial was the best.

rugbert
Mar 26, 2003
yea, fuck you

revmoo posted:

I need to learn Rails in a month, coming from a PHP background. What is the best book to buy?

I thought this was pretty helpful:
http://www.amazon.com/Beginning-Rails-Experts-Voice-Development/dp/1430224339/ref=sr_1_2?ie=UTF8&qid=1307572811&sr=8-2

8ender
Sep 24, 2003

clown is watching you sleep
I started with the Poignant guide to Ruby and then moved to Agile Development with Rails and it was an easy transition from Java.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Bosnian! posted:

Hi folks, I have a quick question that I am sure someone can tell me the answer to. Please bear with me, I am very very new to web programming and as such probably look pretty dumb with this. I have a web service that is producing a JSON file for me for a faculty directory mobile app I am creating using Ruby. My question is given the following format of my JSON output, how would I go about displaying each element on the page? Here is my exact JSON format:
code:
{
    class: "LNameResponse class is here"
      - people: [
            - {
                + class: "FacPerson class is here"
                + email: "personsemailishere"
                + firstName: "firstnameishere"
                + lastName: "lastnameishere"
                + phoneNumber: "phonenumberishere"
                + streetLine1: "address1ishere"
                + streetLine2: "address2ishere"
                + streetLine3: "address3ishere"
              },
            - {
                + class: "FacPerson class is here"
                + email: "personsemailishere"
                + firstName: "firstnameishere"
                + lastName: "lastnameishere"
                + phoneNumber: "phonenumberishere"
                + streetLine1: "address1ishere"
                + streetLine2: "address2ishere"
                + streetLine3: "address3ishere"
              }
      ]
}
I am basically getting this back except add another 3-4 people in the people array. I can verify through my log file that the JSON is being returned from the web service and the values are correct. What I would like is to display this information in my view for each person in the people array one at a time. I know how to loop through and do this but everytime I try to access the people array I get a nil:nilclass error. Not sure what to do, any help would be appreciated.

And sorry if this just sounds like sheer and complete jibberish, I am not too good at explaining problems sometimes.

So you're getting "JSON" that uses pluses and minuses instead of commas? What's the output from the JSON parser you're using (you can see and play with this non-destructively using the rails console).

Oh My Science
Dec 29, 2008
I'm at my wits end, or maybe I'm too tired.

This is my first time using carrierwave, and for some reason I am having a hell of a time getting lightwindow to work correctly with it. (or any lightbox for that matter)

code:
<%= lightwindow_link_to(
	image_tag(artwork.image_url(:thumb)), artwork.image_url(:large), 
        :title => "This is a test!",
	:author=>"Carlo Bertini",
	:caption=>"Ruby on rails is beautyfull :D",
) %>
I have it all connected properly, however the url returned from artwork.image_url(:large) has a trailing / resulting in a lightwindow with a string in it.

How can I remove the trailing /, or is there a better solution for my lightbox needs?

Edit: Figured it out. The lightwindow plugin must be depreciated.

Oh My Science fucked around with this message at 08:35 on Jun 10, 2011

Pardot
Jul 25, 2001




Oh My Science posted:

How can I remove the trailing /, or is there a better solution for my lightbox needs?

Edit: Figured it out. The lightwindow plugin must be depreciated.
code:
>> "abcdefg"[0..-2]
=> "abcdef"

artwork.image_url(:large)[0..-2]
mayhaps if you still want to use that plugin.

Oh My Science
Dec 29, 2008

Pardot posted:

mayhaps if you still want to use that plugin.

Thanks, but I decided to go with topup since it seems to have better documentation.

I have a new problem now, and it's about using kaminari for pagination.

My app is basically a simple photo gallery, and although I have pagination working for the gallery index method, I need to limit how many images are displayed using the show method as well.

It looks like this.

code:
class GalleriesController < ApplicationController
  def index
    @galleries = Gallery.page(params[:page]).per(5)
  end

  def show
    @gallery = Gallery.find(params[:id])
  end

.
.
.

end
What do I need to insert into the controller or model in order to limit the number of images found in a gallery?

I can provide more code if necessary.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Oh My Science posted:

Thanks, but I decided to go with topup since it seems to have better documentation.

I have a new problem now, and it's about using kaminari for pagination.

My app is basically a simple photo gallery, and although I have pagination working for the gallery index method, I need to limit how many images are displayed using the show method as well.

It looks like this.

code:
class GalleriesController < ApplicationController
  def index
    @galleries = Gallery.page(params[:page]).per(5)
  end

  def show
    @gallery = Gallery.find(params[:id])
  end

.
.
.

end
What do I need to insert into the controller or model in order to limit the number of images found in a gallery?

I can provide more code if necessary.

code:
@gallery.images.page([…])

Oh My Science
Dec 29, 2008
Argh, I still don't get it. Here is some more information, hopefully someone can show me what I am doing wrong.

controller :
code:
class GalleriesController < ApplicationController
  # GET /galleries
  # GET /galleries.json
  def index
    @galleries = Gallery.page(params[:page]).per(4)

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @galleries }
    end
  end

  # GET /galleries/1
  # GET /galleries/1.json
  def show
    @gallery = Gallery.find(params[:id])
    @gallery.photos.page(:pagina).per(2)
    
    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @gallery }
    end
  end
index view:
code:

<% @galleries.each do |gallery| %>
  <tr>
    <td><%= gallery.name %></td>
    <td><%= link_to 'Show', gallery %></td>
    <td><%= link_to 'Edit', edit_gallery_path(gallery) %></td>
    <td><%= link_to 'Destroy', gallery, confirm: 'Are you sure?', method: :delete %></td>
  </tr>
<% end %>
</table>

<%= paginate @galleries %>  <-- THIS WORKS
show view:
code:

<h2>Photos</h2>
<% @gallery.photos.each do |photo| %>
  <p>
    <b>title:</b>
    <%= photo.title %>
  </p>
	<%= image_tag photo.photo_url(:thumb) if photo.photo? %>
<% end %>

<%= paginate @gallery %>  <--- THIS PRODUCES UNDEFINED METHODE 'CURRENT_PAGE'
I recreated a really simple version to just play with this, and I still have no luck. As before I have pagination working on my index view, however I cannot get it working on my show view.

How would I use kaminari to paginate the photos in the show view?

Obsurveyor
Jan 10, 2003

Oh My Science posted:

How would I use kaminari to paginate the photos in the show view?
code:
<%= paginate @gallery.photos %>
perhaps?

Oh My Science
Dec 29, 2008

Obsurveyor posted:

code:
<%= paginate @gallery.photos %>
perhaps?

Nope, I have tried many variations to no avail.

Edit: loving got it. Thanks for the help.

Oh My Science fucked around with this message at 01:21 on Jun 12, 2011

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Oh My Science posted:

code:
    @gallery = Gallery.find(params[:id])
    @gallery.photos.page(:pagina).per(2)

Did you forget params[:pagina]?

Also, thanks for using Ruby 1.9 :)

Oh My Science
Dec 29, 2008

BonzoESC posted:

Did you forget params[:pagina]?

Also, thanks for using Ruby 1.9 :)

Yup I think that was the problem. I wish the documentation was more clear about that.

Jam2
Jan 15, 2008

With Energy For Mayhem
Super basic question.

What's the problem with this code?

code:
class Numeric
	def Numeric.squared(x)
		x * x
	end
end

puts 9.squared
puts 16.squared

Only registered members can see post attachments!

Pardot
Jul 25, 2001




Jam2 posted:

Super basic question.

What's the problem with this code?

code:
class Numeric
	def Numeric.squared(x)
		x * x
	end
end

puts 9.squared
puts 16.squared
You defined a class method on numeric, not an instance method.

With yours you could do this
code:
>> 3.class.squared(20)
=> 400
Which isn't really what you want. Here is what you want:
code:
class Numeric
  def squared
    self * self
  end
end

>> 3.squared
=> 9
Also, just as a heads up when you want to make a class method in the future for real, you don't need to repeat the class name, you can just do def self.class_method_name

Randuin
Dec 26, 2003

O-Overdrive~
I see alot of dislike for Devise here, what do people use instead? Roll their own?

Jam2
Jan 15, 2008

With Energy For Mayhem

Pardot posted:


Also, just as a heads up when you want to make a class method in the future for real, you don't need to repeat the class name, you can just do def self.class_method_name
Would you mind explaining this a bit more?

smug forum asshole
Jan 15, 2005

Jam2 posted:

Would you mind explaining this a bit more?

self refers to your Numeric class in that context, so it's perfectly OK to do what Pardot was suggesting.

inside of class Numeric, the following two blocks of code are identical:
code:
def Numeric.squared(x)
  x * x
end
code:
def self.squared(x)
  x * x
end
There is at least one other way to define a class method too! I think it comes down to a matter of personal preference.

smug forum asshole fucked around with this message at 16:16 on Jun 12, 2011

NotShadowStar
Sep 20, 2000

smug forum rear end in a top hat posted:

self refers to your Numeric class in that context, so it's perfectly OK to do what Pardot was suggesting.

inside of class Numeric, the following two blocks of code are identical:
code:
def Numeric.squared(x)
  x * x
end
code:
def self.squared(x)
  x * x
end
There is at least one other way to define a class method too! I think it comes down to a matter of personal preference.

code:
class Numeric
  class << self
    def squared(x)
      x * x
    end
  end
end
When you understand class << self and can explain it in your own words, you've hit master level Ruby and win the game.

hepatizon
Oct 27, 2010

NotShadowStar posted:

code:
class Numeric
  class << self
    def squared(x)
      x * x
    end
  end
end

Does this technique produce any "class instance variable"-style quirks in subclasses, or is it just a regular class method?

Pardot
Jul 25, 2001




hepatizon posted:

Does this technique produce any "class instance variable"-style quirks in subclasses, or is it just a regular class method?

They're just regular class methods, it's just a nicer way to define several in a row.

Also I held off posting about it, waiting for someone else to do it first, but has anyone tried the new cedar stack yet? It's really cool, but I don't want to go on and on about it for fear it'd end up sounding like a sales pitch.

Jam2
Jan 15, 2008

With Energy For Mayhem

NotShadowStar posted:

When you understand class << self and can explain it in your own words, you've hit master level Ruby and win the game.

I apologize if this comes across as dense. Is the << operator being used as append in this case?

I'm reading a Ruby book and come across some this:

The Ruby Programming Language posted:

Many of Ruby's operators are implemented as methods, and classes can define (or redefine) these methods however they want. (They can't define completely new operators, however; there is only a fixed set of recognized operators.) As examples, notice that the + and * operators behave differently for integers and strings. And you can define these operators any way you want in your own classes. The << operator is another good example. The integer classes Fixnum and Bignum use this operator for the bitwise left-shift operation, following the C programming language. At the same time (following C++), other classes—such as strings, arrays, and streams—use this operator for an append operation. If you create a new class that can have values appended to it in some way, it is a very good idea to define <<.

Pardot
Jul 25, 2001




Jam2 posted:

I apologize if this comes across as dense. Is the << operator being used as append in this case?

It is not append in this case. It's getting at the metaclass.

code:
self # => main

Array.hi rescue "no method yet" # => "no method yet"
class << Array
  self # => #<Class:Array>
  def hi
    "hello"
  end
end
Array.hi # => "hello"


some_str = "hey sup"
some_str.what rescue "no method yet" # => "no method yet"
class << some_str
  self # => #<Class:#<String:0x10015c8f8>>
  def what
    self # => "hey sup"
    self.reverse
  end
end
some_str.what # => "pus yeh"

some_str.what2 rescue "no method yet" # => "no method yet"
def some_str.what2
  self # => "hey sup"
  self.size
end
some_str.what2 # => 7

"some other string".what rescue "never got the method" # => "never got the method"
This is probably the best post about it: http://yehudakatz.com/2009/11/15/metaprogramming-in-ruby-its-all-about-the-self/

NotShadowStar
Sep 20, 2000
If you don't get the intracies of the difference between def self.method_name and class << self; def method_name don't worry about it at all. Like I said this is PhD level Ruby and in almost all instances you don't care about the difference; and if you do care about the difference then you should take a hard look at what you're doing because it's probably too convoluted.

Adbot
ADBOT LOVES YOU

smug forum asshole
Jan 15, 2005
Thanks for the explanation and link Pardot. :)

Pardot, are you using a plugin to get the #=> output at the end of each line of code? I googled up the irb_rocket extension, and it looks like what I want.

Pardot's post has me thinking: I sometimes wish I knew more about IRB. Anyone have opinions/suggestions on configuration or plugins to use to extend it?

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