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
Hop Pocket
Sep 23, 2003

If anyone likes watching Ruby conference talks, these links came my way:

http://goruco2008.confreaks.com/
http://mtnwestrubyconf2008.confreaks.com/

About 3.5 GB of nicely formatted talks (so far).

Adbot
ADBOT LOVES YOU

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!
I'm trying to figure out how to farm off some code in one of the railcasts into a helper. It's from #74: Complex Forms Part 2.

code:
<!-- projects/_task.rhtml -->
<div class="task">
<% fields_for "project[task_attributes][]", task do |task_form| %>
  <p>
    Task: <%= task_form.text_field :name %>
    <%= link_to_function "remove", "$(this).up('.task').remove()" %>
  </p>
<% end %>
</div>
I want to put that removal code into a helper, but I can't figure out how to pass along that this pointer. Does anybody have an idea? I'm trying to use that code as a base for removing some data from a table.

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!
I kind of sort of got beyond that. I ended up having to tag the rows with unique identifiers; I couldn't find a way to have it dynamically move relative up in the DOM and delete itself from within a helper. The problem I have now is that Ruby code in my link_to_function gets evaulated immediately, rather than when the event triggers. I guess it doesn't completely surprise me, but I need something like lazy evaluation.

The problem is that I am trying to remove things from an array within a link_to_function field. Since that gets evaluated when the page is rendered, it starts deleting immediately. The block looks like this:

code:
    <td><%= link_to_function "Remove" do |page|
        print "REMOVE DO BODY\n"
        remove_fermentable(page, @fermentables, idx)
	end
	 %>
    </td>
My server console output prints "REMOVE DO BODY" when I request the page. Is there something I can do so that the code is instead embedded into my page and only triggers when I click "Remove?"

Hop Pocket
Sep 23, 2003

Rocko Bonaparte posted:

My server console output prints "REMOVE DO BODY" when I request the page. Is there something I can do so that the code is instead embedded into my page and only triggers when I click "Remove?"

Are you wanting the code to execute on the server when it is clicked? If so you should probably look at link_to_remote.

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!

Hop Pocket posted:

Are you wanting the code to execute on the server when it is clicked? If so you should probably look at link_to_remote.
I'll try it. What needs to happen is when the link is clicked:

1. The row disappears from the client's screen.
2. The server's understanding of the list removes that row.

Could I have that all done on the client side anyways? Really the server doesn't need to know that stuff.

skidooer
Aug 6, 2001

Rocko Bonaparte posted:

2. The server's understanding of the list removes that row. ... Really the server doesn't need to know that stuff.
If the server needs to know:
code:
<% content_tag_for(:tr, task) do %>
  <td>
    <%=h task.name %>
  </td>
  <td>
    <%= link_to_remote 'remove', :url => task_path(task), :method => :delete %>
  </td>
<% end %>
code:
class TasksController < ApplicationController
  def destroy
    @task = Task.find(params[:id])
    
    if @task.destroy
      render :update do |page|
        page.remove dom_id(@task)
      end
    end
  end
end
If it doesn't:
code:
<% content_tag_for(:tr, task) do %>
  <td>
    <%=h task.name %>
  </td>
  <td>
    <%= link_to_function('remove') { |link| link.remove(dom_id(task)) } %>
  </td>
<% end %>

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!

skidooer posted:


If it doesn't:
code:
<% content_tag_for(:tr, task) do %>
  <td>
    <%=h task.name %>
  </td>
  <td>
    <%= link_to_function('remove') { |link| link.remove(dom_id(task)) } %>
  </td>
<% end %>
Somehow though I need to remove the item from the array I'm using. Would that have to happen on the server, or will rails chew that up into JavaScript that can happen properly on the client side? I was hoping that the client side can do all the math involved with calculations in the array, so it would have to know of it and be able to manage it.

The server is there to pump down the initial page, and hopefully provide data for things that could be populated into the array.

Edit: Just to get back to the core problem, I need the system--be it client or server--to not remove elements from the array when the page is first loaded. It should only happen when when the link is clicked. Right now, it's deciding to nuke the specified element from the array each time I create the removal link. So my page is creating, say, 3 items. I get to the point where I'm making the view. Each time I add a link_to_function that has the array removal code in the body, it's actually executing it right on the spot. So by the time the page is done loading, I have nothing in my array anymore.

Rocko Bonaparte fucked around with this message at 21:03 on May 8, 2008

skidooer
Aug 6, 2001

Rocko Bonaparte posted:

Edit: Just to get back to the core problem, I need the system--be it client or server--to not remove elements from the array when the page is first loaded. It should only happen when when the link is clicked.
I think we need to see some more code. What exactly is in this array?

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!

skidooer posted:

I think we need to see some more code. What exactly is in this array?

Right now the array is created in the controller:
code:
class RecipeController < ApplicationController


  def index

    @fermentables = []
    @fermentables.push(Fermentable.new("6-row", 5, 2, 44, 1.50))
    @fermentables.push(Fermentable.new("Crystal 40L", 1, 40, 38, 2.25))
    @fermentables.push(Fermentable.new("Black Patent", 0.25, 400, 4, 2.33))

      respond_to do |format|
         format.html # index.html.erb
      end

  end

end
Each Fermentable gets a row in a table. That row is done in a partial here:
code:
<!-- Parameter: idx, Index of fermentable to display -->
<!-- Parameter: fermentables, fermentables list from which to manipulate elements -->

  <tr id=
    <%= fermentables[idx].get_tag() %>
  >

    <!-- Function is incomplete -->
    <td><%= link_to_function "Prepend" do |page|
        prepend_fermentable(page, @fermentables, idx) 
	end
	%>
    </td>

    <!-- Function is incomplete -->
    <!-- "$(this).up('.fermentable').remove()" -->
    <!-- remove_fermentable("this") -->
    <td><%= link_to_function "Remove" do |page|
        remove_fermentable(page, @fermentables, idx)
	end
	 %>
    </td>

    <td><%= fermentables[idx].substance %></td>
    <td><%= fermentables[idx].quantity  %></td>
    <td>lb</td>
    <td><%= fermentables[idx].lovlb     %></td>
    <td><%= fermentables[idx].SGlb      %></td>
    <td><%= fermentables[idx].costlb    %></td>

  </tr>
The code for remove_fermentable is in a helper:
code:
       def remove_fermentable(page, fermentables, index)
          page.remove(fermentables[index].get_tag())
	  print "Deleting element\n"
	  fermentables.delete_at index
       end
So what happens is that I get "Deleting element" printed at least twice; the page shits itself and ends up drawing nothing. It's actively deleting the array when the page gets rendered. What I'm intending is that it only deletes from the array when the "Remove" link is clicked by the user--not when the link is initially constructed.

skidooer
Aug 6, 2001

Rocko Bonaparte posted:

Right now the array is created in the controller:
The web is stateless. That array will be recreated on every page load, even if an element has been removed. I'm thinking that's not what you want at all. You will probably want to rethink your application design, but without changing what you have too much:

fermentables_controller.rb
code:
class FermentablesController < ApplicationController
  before_filter :set_fermentables
  
  def destroy
    fermentable = @fermentables[params[:id].to_i]
    @fermentables.delete(fermentable)
    
    render :update do |page|
      page.remove(fermentable.get_tag)
    end
  end
  
  private
    def set_fermentables
      @fermentables = session[:fermentables] ||= [
        Fermentable.new("6-row", 5, 2, 44, 1.50),
        Fermentable.new("Crystal 40L", 1, 40, 38, 2.25),
        Fermentable.new("Black Patent", 0.25, 400, 4, 2.33)
      ]
    end
end
index.html.erb
code:
<table>
  <%= render :partial => @fermentables %>
</table>
_fermentable.html.erb
code:
<tr id=<%= fermentable.get_tag %>>
  <td><!-- Not sure what prepend does --></td>

  <td><%= fermentable.substance %></td>
  <td><%= fermentable.quantity %></td>
  <td>lb</td>        
  <td><%= fermentable.lovlb %></td>
  <td><%= fermentable.SGlb %></td>
  <td><%= fermentable.costlb %></td>
	
  <td><%= link_to_remote 'Remove',
	          :url => fermentable_path(fermentable_counter),
	          :method => :delete %>
</tr>

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!

skidooer posted:

The web is stateless. That array will be recreated on every page load, even if an element has been removed. I'm thinking that's not what you want at all. You will probably want to rethink your application design, but without changing what you have too much:

No I actually wanted a new array on each load of that page. I was hoping my tool would come up and I could just interact with that. The default data I had in there is just for experimenting, but normally that would initially come up blank, and I would start adding my things in.

Really, it's more like a client application that I want to be able to run from any computer with a browser.

Update: I've read up a little bit more on all this stuff. What I want to try to do is get the client aware of all these objects and arrays, and have all the work done client-side. The server would initially serve the page, and occasionally do some AJAX goodness to give the client some data. Right now, the array is declared in the controller. I don't see it get declared on the page that is generated for the client, so the client has no awareness of the array. Is there a way--using Ruby code--to declare the array on the client side?

Also, I know I can use link_to_function to handle a line of JavaScript, but is there a way to use Ruby code and have rails turn it into JavaScript when rendered? I am trying to reduce the amount of languages I'm throwing around in this app. Sure, it can be JavaScript when it's run, but I'm trying to make it Ruby code that I am actually typing.

Rocko Bonaparte fucked around with this message at 18:11 on May 9, 2008

bag of a bee
Jun 17, 2007

skidooer posted:

You can use fields_for to specify an additional object.
...code stuff...

Thanks, this worked perfectly :)

I'll also have to check out those rubycast because I've got no idea what's going on with this code here.

dustgun
Jun 20, 2004

And then the doorbell would ring and the next santa would come
This is more of a general ruby question, but how the hell do I unpack a utf8 string in ruby 1.8 and get it so that \xC2\xAE actually shows up as ® in the output? I've never really done this stuff, and feel sort of lost googling around.

dustgun
Jun 20, 2004

And then the doorbell would ring and the next santa would come
DoubleDamnit post

Pardot
Jul 25, 2001




dustgun posted:

This is more of a general ruby question, but how the hell do I unpack a utf8 string in ruby 1.8 and get it so that \xC2\xAE actually shows up as ® in the output? I've never really done this stuff, and feel sort of lost googling around.

This may work for you:

code:
[b]>> s = "\xC2\xAE"[/b]
=> "\302\256"
[b]>> s.to_[/b]
[i]s.to_a    s.to_f    s.to_i    s.to_s    s.to_str  s.to_sym  [/i]
[b]>> require 'activesupport'[/b]
=> true
[b]>> s.to_[/b]
[i]s.to_a        s.to_date       s.to_datetime     s.to_enum             s.to_i             s.to_json
s.to_param    s.to_query      s.to_s            s.to_set              s.to_str           s.to_sym
s.to_time     s.to_xs         s.to_yaml         s.to_yaml_properties  s.to_yaml_style    s.to_f[/i]
[b]>> s.to_xs[/b]
=> "&[i][/i]#174;"

Pardot fucked around with this message at 01:32 on May 26, 2008

dustgun
Jun 20, 2004

And then the doorbell would ring and the next santa would come
Perfect, thanks.

Pardot
Jul 25, 2001




Anyone going to be at railsconf?

thevortex
Jul 2, 2002

RETURN... FROM WHENCE YOU CAME!

Pardot posted:

Anyone going to be at railsconf?

I'm on the train from Seattle, heading down right now.

Cylon Dinner Party
Dec 2, 2003

bored now.
Can I inherit from a class defined in a module?

code:
require 'rexchange' # RExchange defines a class called Message

class Smsg < Message
# blah
end
This yields "uninitialized constant Message (NameError)"

skidooer
Aug 6, 2001

Cylon Dinner Party posted:

Can I inherit from a class defined in a module? ...
class Smsg < Message
class Smsg < ModuleName::Message ...

Cylon Dinner Party
Dec 2, 2003

bored now.

skidooer posted:

class Smsg < ModuleName::Message ...

Thanks! You came through where my google fu failed. Please accept my apologies, if the Rails thread is not meant to double as Ruby Stupid Questions.

Pardot
Jul 25, 2001




Cylon Dinner Party posted:

Thanks! You came through where my google fu failed. Please accept my apologies, if the Rails thread is not meant to double as Ruby Stupid Questions.

I mentioned this in the merb thread too, but I think a general ruby megathread would be better. I'm sure the tread would be just like this one, mostly rails but some random ruby stuff.

Maybe we should just get the name of this thread changed.

Nigger Goku
Dec 11, 2004

あっちに行け
Is there a way to break/continue multiple levels in Ruby?

Say I have a each loop inside an each loop, and I want to the inner loop to be able to issue a continue to the outer one.

This would be an example case:
code:
dirs.each do |dir|
  dir.each do |file|
    if file.something?
      next 2 #break dir.each and do a next on dirs.each
    end
    #Do something with file
  end
  #Do something with dir
end
If it's not possible to break multiple levels, how should I go about dealing with nested loops and flow control?

skidooer
Aug 6, 2001

Opius posted:

If it's not possible to break multiple levels, how should I go about dealing with nested loops and flow control?
The best way is to not introduce it in the first place.

From what you posted, this comes to mind:
code:
dirs.each do |dir|
  dir.reject { |d| d.something? }.each do |dir|
    ...
  end
  ...
end
Depending on what you are trying to do, it may or may not be the best structure to begin with.

Carabus
Sep 30, 2002

Booya.
Not strictly a Rails question, but I am using ActiveRecord to access a database. What is the best way to convert table attributes to a hash? For example:
code:
ratings = { 'User1' => { :'Lady in the Water' => 2.5, 'Snakes on a Plane' => 3.5, 
'Just My Luck' => 3.0, 'Superman Returns' => 3.5, 
'You, Me and Dupree' => 2.5, 'The Night Listener' => 3.0},

'User2 => { :'Lady in the Water' => 3.0, 'Snakes on a Plane' => 3.5, 
'Just My Luck' => 1.5, 'Superman Returns' => 5.0, 
'The Night Listener' => 3.0, 'You, Me and Dupree' => 3.5} } 
I'm a Ruby newb, so it is probably just a lack of familiarity with hash methods. Documentation just isn't enlightening me at the moment.

Carabus fucked around with this message at 19:53 on Jun 16, 2008

skidooer
Aug 6, 2001

Carabus posted:

What is the best way to convert table attributes to a hash?
Depending on your table structure and what you are trying to do exactly, something like this might work:
code:
class Rating < ActiveRecord::Base
  belongs_to :user
  belongs_to :film
  
  def self.grouped_ratings
    find(:all, :include => [ :user, :film ]).inject({}) do |grouped_ratings,rating|
      (grouped_ratings[rating.user.name] ||= {}).merge!(rating.film.name => score)
    end
  end
end

Carabus
Sep 30, 2002

Booya.
I should try to figure this out myself, since I only understand part of your code and my purpose is to actually learn the language. The exercise is from this book. I made a clumsy ruby port of one of the Python scripts from the book, not as good as this version at Github but it works. I have a table to work with which has a columns for user, rating, and rateable. It was easier than I thought to port from Python to Ruby but this has posed a bit bigger challenge for me, even though I know it should be simple.

So if anyone is interested in this sort of thing, take a look and I would appreciate any suggestions but thanks for the help already, skidooer.

unleash the unicorn
Dec 23, 2004

If this boat were sinking, I'd give my life to save you. Only because I like you, for reasons and standards of my own. But I couldn't and wouldn't live for you.
So I've been playing around with Ruby lately, did all the Lucky Stiff stuff and so on, and now that that's been going great I was wondering whether it's possible to make something I created with Shoes into a "real" .exe-File.

Is that even possible with ruby?

Pardot
Jul 25, 2001




unleash the unicorn posted:

So I've been playing around with Ruby lately, did all the Lucky Stiff stuff and so on, and now that that's been going great I was wondering whether it's possible to make something I created with Shoes into a "real" .exe-File.

Is that even possible with ruby?

I could be wrong, but I don't think you can do that with something like shoes. I think the best you can do is do something in jruby and package that into bytecode. I haven't looked into any of this myself, but I think there is at least one jruby UI thing. This is all just vague recollections from my rss feeds, though.

unleash the unicorn
Dec 23, 2004

If this boat were sinking, I'd give my life to save you. Only because I like you, for reasons and standards of my own. But I couldn't and wouldn't live for you.
Hmmm, thanks.

Could anyone point me to a good how-to for making ".shy" files instead? I can't seem to find anything, and googling "ruby shy" leads to some "mygayweb" site which I don't really have the guts to explore.

dustgun
Jun 20, 2004

And then the doorbell would ring and the next santa would come

Pardot posted:

I could be wrong, but I don't think you can do that with something like shoes. I think the best you can do is do something in jruby and package that into bytecode. I haven't looked into any of this myself, but I think there is at least one jruby UI thing. This is all just vague recollections from my rss feeds, though.

quote:

Okay, the latest set:

* http://code.whytheluckystiff.net/dist/shoes-0.r724.exe
(windows + video support; 7.3M)
* http://code.whytheluckystiff.net/dist/shoes-0.r724-intel.dmg
(osx-intel + video support; 7.9M)
* http://code.whytheluckystiff.net/dist/shoes-0.r724.tar.gz
(source; 550K)

This build includes support for packaging Shoes apps as EXEs and
DMGs. This'll be covered in a hackety.org blog post in a few
minutes.

For smaller non-video builds, see the Recent Builds page:
http://code.whytheluckystiff.net/shoes/wiki/RecentBuilds

_why
Just came a few minutes ago :)

unleash the unicorn
Dec 23, 2004

If this boat were sinking, I'd give my life to save you. Only because I like you, for reasons and standards of my own. But I couldn't and wouldn't live for you.
Yeah, I saw that too. Awesome!

HIERARCHY OF WEEDZ
Aug 1, 2005

Okay, Site5 loving sucks. What's the latest round of suggestions for a Rails/Ruby framework friendly host -- and what's the score on hosting providers picking up on Phusion Passenger aka mod_rails?

Damnit going to have to move all my sites again grumble grumble

HIERARCHY OF WEEDZ
Aug 1, 2005

Okay, so since apparently no one is actually deploying Rails projects, I have another question :)

Say we have a User model, and a Recipe model, and Recipe belongs_to a User. If I want to retrieve the number of recipes a user has, I can do something like Recipe.count( :conditions => [ 'recipe_user = ?', user_id], :include => :user), but what if I wanted to cache that number, so it wasn't calculated every time I had a list of thousands of users? Should I just add another table column and run a rake task every 30 minutes or so that re-calculates and UPDATEs that column for the Users table? Or is there a more sensible way of dealing with this?

EDIT: Oh hey, counter_cache. Hooray! See here for details if you have the same question: http://railscasts.com/episodes/23

manero
Jan 30, 2006

shopvac4christ posted:

Okay, Site5 loving sucks. What's the latest round of suggestions for a Rails/Ruby framework friendly host -- and what's the score on hosting providers picking up on Phusion Passenger aka mod_rails?

Damnit going to have to move all my sites again grumble grumble

Not sure about whether if mod_rails is production ready yet. Personally, I have a slice on slicehost.com, but I haven't deployed an app there yet. They also have Rails-ready slices.

At work we use EngineYard. We pay out the rear end, but they make up for the price in the support you get.

Evil Trout
Nov 16, 2004

The evilest trout of them all

shopvac4christ posted:

Okay, so since apparently no one is actually deploying Rails projects, I have another question :)

No, some of us have Rails projects in production. Forumwarz, my MMO, is deployed on a dedicated host.

The technology is Nginx proxying to a pack of Mongrels.

I don't have any recommendations for small projects, but if you are doing mid-sized traffic (right now we're doing 20 dynamic rq/sec) a dedicated server is quite affordable at most hosting companies.

I just assumed that since you said you were interested in Phusion that you were working on something smaller.

HIERARCHY OF WEEDZ
Aug 1, 2005

Grob posted:

No, some of us have Rails projects in production. Forumwarz, my MMO, is deployed on a dedicated host.

The technology is Nginx proxying to a pack of Mongrels.

I don't have any recommendations for small projects, but if you are doing mid-sized traffic (right now we're doing 20 dynamic rq/sec) a dedicated server is quite affordable at most hosting companies.

I just assumed that since you said you were interested in Phusion that you were working on something smaller.

Well, that's the thing. I don't have *any* projects because I don't trust myself to do deployments, and I don't do any deployments because I don't have sufficient hosting, and I don't feel it's necessary to pay out the rear end for hosting on projects that for all intents and purposes aren't valid public projects, but just me playing around with the framework. So it's a conundrum.

jonnii
Dec 29, 2002
god dances in the face of the jews

shopvac4christ posted:

Well, that's the thing. I don't have *any* projects because I don't trust myself to do deployments, and I don't do any deployments because I don't have sufficient hosting, and I don't feel it's necessary to pay out the rear end for hosting on projects that for all intents and purposes aren't valid public projects, but just me playing around with the framework. So it's a conundrum.

Capistrano makes deployment pretty easy. In my case I have an nginx frontend proxying to thin instances. I use god to keep the memory usage in check and backgroundrb running.

HIERARCHY OF WEEDZ
Aug 1, 2005

jonnii posted:

Capistrano makes deployment pretty easy. In my case I have an nginx frontend proxying to thin instances. I use god to keep the memory usage in check and backgroundrb running.

That's what I've heard, but I haven't had a chance to actually try it. That's what I'm asking. Where are people deploying their projects? Their one-off, unimportant stuff? I'm not shelling out 400 dollars a month for an Engine Yard slice. I'm still in college, you know?

Adbot
ADBOT LOVES YOU

hmm yes
Dec 2, 2000
College Slice
Slicehost is priced pretty fairly with their lowest VPS only $20/month. If you can't afford that, you might as well just run things on localhost because I don't think anything else is available. I guess you could try Dreamhost--they are now using Passenger / mod_rails.

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