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
UxP
Aug 27, 2007

Nolgthorn posted:

I believe the current rails 3 auth favourite is devise. http://github.com/plataformatec/devise

I have yet to start any rails 3 apps, but am building a timetable to get some of my 2.3.5 apps over to 3 before the end of the year. Besides the obvious devise blog and railscasts for information, does anyone know of an awesome blog post or tutorial on migrating from Authlogic to Devise?

Adbot
ADBOT LOVES YOU

UxP
Aug 27, 2007

plasticbugs posted:

I basically need to parse through all the "threads", and for each unique thread ID, I need to search across all the "posts" in the XML to find all the entries that share that "thread id". Then, save out a Comment for the matching data.

There isn't much of a reason to separate out the threads and comments loops, just go for it all in one shot. I've never used css selectors for XML node traversal, so I'd honestly just go for basic XPath.

pre:
require 'nokogiri'

doc = Nokogiri::XML(File.open(File.join(Dir.home(), "Downloads", "disqus.xml")))

doc.xpath('/xmlns:disqus/xmlns:thread').each do |t|
  doc.xpath(%Q<//xmlns:post[xmlns:thread[@dsq:id="#{t.attr('id')}"]]>).each do |c|
    comment = Comment.new
    comment.code = t.attr('id')
    comment.author = c.xpath('xmlns:author/xmlns:name').inner_text()
    comment.message = c.xpath('xmlns:message').inner_text()
    comment.save!
  end
end
Edit: Your variable scope is all over the place. @doc doesn't need to be an instance variable, unless this Disqus importer is some kind of class object and casting p as an instance variable is not the way to go. The way you have the inner loop all sorts of confusing. I know what it is supposed to do, but there's no reason to be doing it that way. Keep It Simple (Stupid).

Long story short, @thread_id and @post_id in your script are never going to be the same.

UxP fucked around with this message at 18:07 on Feb 12, 2012

UxP
Aug 27, 2007

Physical posted:

I cannot get it to run though because it is using Rails 2.5 and such and I have no experience with it.

Rails has never had a 2.5.x (or 2.4.x) version. Might you be thinking of 2.3.x?

With rbenv or RVM, it's still amazingly simple to use old screencasts and tutorials in a copy/paste fashion.

code:
$ rvm install 1.8.7
$ rvm use 1.8.7@oldrails
$ gem install rails -v 2.3.14
$ rails myapp
$ cd myapp
Obviously, making sure your gems are version compatible is a must, especially since Rails 2.x doesn't use a Gemfile by default. You can (and I highly suggest) create a Gemfile manually and rely on Bundler to load the correct versions of the extra gems you need. It might be a tad more work for something with a ton of dependancies, but it's not difficult.

UxP
Aug 27, 2007

Here's a less bloated single script POC: https://gist.github.com/4660248

And a writeup: http://ronin-ruby.github.com/blog/2013/01/28/new-rails-poc.html

UxP
Aug 27, 2007

If anyone that reads this thread is not subscribed to that loving mailing list, they're a loving fool. Do it.

UxP
Aug 27, 2007

MrDoDo posted:

You can use the debugger gem if you are just using a regular text editor. I have found IDEs like RubyMine to be pretty nice though at giving you a visual debugging environment when you are first starting out.

The Debugger gem supports remote connections for people less inclines to Kitchen Sink IDEs, which I've found super loving useful as of late. Somewhere in the boot process of your app (like inside 'config/environments/development.rb') toss this in

code:
require 'debugger';
Debugger.start_remote
Then, anywhere else in your application just throw in the same "debugger" call as you would otherwise. If you run your app at this exact moment, you might notice that the debugger seems to pass over the breakpoint. But no fear, in another terminal window, connect to the debugger session with `rdebug -c`, and the next time you pass over that debug breakpoint it'll catch and you can do your thing.

'ruby-debug' for 1.8.x also supports this exact same thing, FWIW. There's some very sparsely documented features around that, like the ability to pass in the host and port you bind to so you can run concurrent remote debugging sessions (for like a web worker and a job worker), or truly remote sessions.

Thought I'd just throw this info out there. Doesn't seem like many people know about this. If anyone uses Pow, now you don't have any excuse for not debugging.

UxP
Aug 27, 2007

Lexicon posted:

^ That's cool, but why is it preferable over simply adding the debugger gem to your Gemfile, and then inserting `debugger` at the point of interest? I do this all the time, and it hits the break in the console I'm using to run either rails server or rails console.

I work inside a very service-oriented architecture, which means a full integration test or manual walk through the UI requires 4 or 5 applications to be running at any one given time. Pow tries to solve this problem by allowing me to symlink my application root to a dot-folder in my home directory, and maintains a pseudo-DNS service to route any requests for "my_app.dev/" to the "my_app" symlink. I don't need to maintain 4 different terminal windows running "rails server", manually configuring differing localhost ports to not conflict.

It might not be preferable over a simple "require 'debugger'; debugger; 0;" line wherever you need for simple standalone applications. I wasn't trying to imply that debugging through a remote console is a better practice of which everyone should switch to, but that it's a tool available for the situations where one might need it. The discussion of debugging came up, and I had coincidentally just recently showed several co-workers Pow and this feature when one was complaining about having to maintain multiple app's console windows at one time, and wished for a simpler solution.

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.

UxP
Aug 27, 2007

Siguy posted:

Was Rails 4.0 delayed by all the security fixes? For some reason I thought it was supposed to be out by now.

No. It's only been a month and 2 days since beta1 was released. Release candidates will still be some months out.

UxP
Aug 27, 2007

Lexicon posted:

Ruby code:
first = WhateverObject.inject([ ], &:my_block)

I know you figured it out, but the proc passing syntax is something that kinda hung me up for a while, and still catches me off-guard.

The only time I can remember seeing `&:symbol` syntax is the mapEnumerable short-circuit like this contrived example:

Ruby code:
[ 1, 2, 3 ].map(&:to_s) # => ["1", "2", "3"]
&thing is generally used to signify a proc object (and blocks are basically anonymous procs), so you'll need to assume that in &:symbol, the symbol name would have to be a method defined on the class it calls, by Symbol.to_proc.

Ruby code:
myproc = :add_fortytwo.to_proc

[ 1, 2, 3 ].map(&myproc) # => NoMethodError: undefined method `add_fortytwo' for 1:Fixnum

class Fixnum
  def add_fortytwo
    self + 42
  end
end

[ 1, 2, 3 ].map(&myproc) # => [43, 44, 45]
# or more directly:
[ 1, 2, 3 ].map(&:add_fortytwo) # => [43, 44, 45]

More info on this, which was dubbed the "Blockinator syntax" by Dave Thomas:
http://pragdave.pragprog.com/pragdave/2005/11/symbolto_proc.html
http://blog.jayfields.com/2007/01/ruby-invoking-method-with.html

UxP fucked around with this message at 19:02 on Apr 7, 2013

UxP
Aug 27, 2007
Are you trying to create the base, db backed object as "Record", and then namespace it's children under it, like this?

Ruby code:
class Widget < ActiveRecord::Base
  attr_accesible :name

end

class Widget
  class Twirlymajig < Widget
    attr_accessible :sprockets

  end
end
This is technically valid ruby code from what I understand, my co-worker just said I'm wrong. Inheriting from your parent is not valid, but it will manage to run on some occasions. Most specifically, you're always required to load the full base class first, else Rails will complain about the child class not defining it's constant in the global space because the first class declaration in the file doesn't match the inflected file name, and then once you resolve that, you'll end up with the parent class being treated as a module on some occasions.

You'd have better luck defining a base class inside a module and inheriting all your children from that.
Ruby code:
# in app/models/widget.rb
module Widget
  # base namespace for Base, Twirlymajog, and Sprocket,
end

# in app/models/widget/base.rb
module Widget
  class Base < ActiveRecord::Base
    attr_accessible :name

  end
end

# in app/models/widget/twirlymajig.rb
module Widget
  class Twirlymajig < Base
    attr_accessible :sprockets

  end
end

UxP fucked around with this message at 00:20 on Apr 13, 2013

UxP
Aug 27, 2007

Lexicon posted:

I've got an ActiveRecord model with an metadata field that I'd like to be a hash in ruby-land, but be serialized to the database as JSON. Ideally, this conversion would all be handled nicely by before_save hooks and so forth.

What's the best way to go about this?

Depends on which version of ActiveRecord you're using, but you should be able to do this with >= 3.1

Ruby code:
class Post < ActiveRecord::Base
  serialize :metadata, JSON

end
Otherwise, here's a Gem I've recently converted from an old plugin to do the same thing, but with Marshal data instead of JSON. The idea should be identical: https://github.com/uxp/marshalled_attributes

UxP
Aug 27, 2007

DreadCthulhu posted:

Question for you Rails experts: how does Rails decide what environment the code is running as? Is ruby reaching out to the shell and checking that a certain environment variable is set correctly?

On that note, do you know how the web app decides what database to talk to when it receives a call? For example, say I'm running functional tests that hit Postgres. Does every single ActiveRecord call check the environment variable? Does the test suite just reset it back to what it was before once it's done?

Kind of, yeah: https://github.com/rails/rails/blob/master/railties/lib/rails.rb#L56

ActiveRecord memoizes the environment so it won't actually call out to find the environment on every request. Ruby itself will populate the ENV hash with your shell's environment variables. Start up an irb session and call that magic object, it should be identical to calling env from bash or zsh or whatever.

UxP
Aug 27, 2007

DreadCthulhu posted:

So by default the cookies are signed and basically given full trust regarding whether the user is who he claims he is? Permissions in there as well?

Yes. Signing them isn't a magic solution, but it prevents anyone from actually tampering with a cookie to change their user_id or role, or whatever you happen to store in a cookie, as long as no one knows what your session secret is ( 'config/initializers/secret_token.rb' ), as long as OpenSSL's HMAC remains trusted.

Adbot
ADBOT LOVES YOU

UxP
Aug 27, 2007

Mr Man posted:


code:
<%= form_for(followitem(follow: @item)) do |f| %>
  <div><%= f.hidden_field :follow %></div>
  <%= f.submit "Follow", class: "btn btn-large btn-primary" %>
<% end %>
and in my item_helper.rb

code:
def followitem(it)
   current_user.follow!(it)
end
Now I'm getting an error back saying that the item is not followable.... Anyone know what I'm doing wrong?

First off, your form isn't set up right. You're trying to pass in the followitem method as the object you're building a form for, and you're passing in a hash to the followitem method when it's expecting an object marked as 'acts_as_followable' or some poo poo. Take a step back and think about what you're actually trying to do.

Here's two simple rules:

1) you cant pass an object from the client to the server, you can only pass representations and identifiers of that object.
2) you can't run ruby code on the client.

So, this means you need to set up a link that POSTs back an ID of an Item object of which the current user is wanting to follow. Whether you do that by a form and hidden ID, or a simple `link_to "Follow!", follow_item_path(item), :method => :post` with a constrained route is up to you (eg, '/users/4/follow/8'). The goal of this is to just pass the ID of the Item object. Nothing more. Then, in your controller, you need to search for the item with the ID you passed in from the client, and then call the current_user.follow!(item) method using the object you found through ActiveRecord.

This is a good candidate for an Ajax request, which it seems like you're trying to do, but before you even think about that get it working with plain old http request/response.

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