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
Anveo
Mar 23, 2002
URI.extract + ruby-oembed will get you pretty far. More on oEmbed here.

Adbot
ADBOT LOVES YOU

dustgun
Jun 20, 2004

And then the doorbell would ring and the next santa would come
http://embed.ly/ can also be useful for such things.

edit: woop, ruby-oembed apparently can use embedly. Carry on.

dustgun fucked around with this message at 22:10 on Dec 28, 2010

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

dustgun posted:

http://embed.ly/ can also be useful for such things.

edit: woop, ruby-oembed apparently can use embedly. Carry on.

Oh man.

When URI was suggested, while researching it I found the Addressable gem. While reading about Addressable, I found ruby-oembed. While reading about ruby-oembed I found embedly. Pretty much every single time I came back to the thread, the next thing was suggested.

Embedly is unbelievably awesome. It's still a bit quirky, often links to news websites don't work. But for now, it's exactly what I need.

Here is what I've worked out.


code:
class Embedly
  def self.get_attrs(url)
    embedly_url = "http://api.embed.ly/1/oembed?url=#{url}"
    response = RestClient.get embedly_url
    attrs = JSON.parse response.body
  rescue
    {}
  end
end
code:
class Link
  [..blah blah blah]

  before_validation :set_attrs_via_embedly, :on => :create
  
  protected

  def set_attrs_via_embedly
    attrs = Embedly.get_attrs(url)
    if ["photo", "video", "rich", "link"].include? attrs[:type]
      self.type = attrs[:type]
      self.provider_name = attrs[:provider_name]
      self.title = attrs[:title]
      self.thumbnail_url = attrs[:thumbnail_url]
      self.thumbnail_width = attrs[:thumbnail_width]
      self.thumbnail_height = attrs[:thumbnail_height]
      self.description = attrs[:description]
    end
  end
end
It's like magic. Thanks everybody!


e: This was nicked from here: http://trevorturk.com/2010/06/27/using-embedly-the-quick-and-dirty-way/

Nolgthorn fucked around with this message at 01:53 on Dec 29, 2010

JonM1827
Feb 2, 2007
I guess this is more of a ruby question, but I'm using it in a rails app so I guess it still works here...

I'm tying to compare to times, and the way I'm doing seems to work, I'm just sure there has to be a better way.

Basically, I'm querying an API that returns a time in "20101229 22:28" format, and I want to take the difference and return a string of that, but just in minutes.
code:
now = Time.parse(e.elements['tmstmp'].text)
arrival = Time.parse(e.elements['prdtm'].text)
...
ret << ((arrival - now)/60).to_s
Thanks in advance for any help!

ninja edit: I tried to do a quick search for this through the thread but didn't see anything, sorry if I missed it.

JonM1827 fucked around with this message at 05:37 on Dec 30, 2010

NotShadowStar
Sep 20, 2000
Close, but Ruby's Time class is :krad: and the Time extensions in ActiveSupport are even more :krad:
code:
ret = (arrival - now).min
http://ruby-doc.org/core/classes/Time.html
http://api.rubyonrails.org/classes/Time.html

JonM1827
Feb 2, 2007

NotShadowStar posted:

Close, but Ruby's Time class is :krad: and the Time extensions in ActiveSupport are even more :krad:
code:
ret = (arrival - now).min
http://ruby-doc.org/core/classes/Time.html
http://api.rubyonrails.org/classes/Time.html

Hmm... thanks for the quick reply, but I had actually tried that and got an error.

code:
now = Time.parse(e.elements['tmstmp'].text)
arrival = Time.parse(e.elements['prdtm'].text)
diff = (arrival - now).min

$ ruby test.rb
...
undefined method `min' for 1140.0:Float (NoMethodError)
...
Thoughts?

edit:
I just tried doing:
code:
diff = (arrival.min - now.min)
and that does seem to work, strange...

JonM1827 fucked around with this message at 06:05 on Dec 30, 2010

manero
Jan 30, 2006

JonM1827 posted:

I just tried doing:
code:
diff = (arrival.min - now.min)
and that does seem to work, strange...

You're only figuring out the difference in the *minutes*, not the actual times. Thusly:

code:
>> a = Time.now
=> Thu Dec 30 23:12:09 +0000 2010
>> b = 3.weeks.ago
=> Thu Dec 09 23:12:13 +0000 2010
>> (a.min - b.min)
=> 0
A Time minus a Time returns a distance in seconds, I believe.

Edit for succinctness.

rugbert
Mar 26, 2003
yea, fuck you
Ive made a blog and in the model I have a column for categories. Whats the easiest way to I guess, filter those categories like a wordpress blog?

I was hoping I could make a link_to that was something like
code:
<%= link_to "category name", blogs_path(params[:category => category_name])  %>
Or something like that. What I have no doesnt actually do anything. It just reloads the blog page :/.
Basically, I want to pass in the category name so that the blog index will ONLY load the blogs of a certain category

NotShadowStar
Sep 20, 2000
Easiest
1) Make a category method on your blog controller
code:
def category
  @posts = Post.where(:category => params[:category])
end
2) Create a route
code:
#the :as parameter creates a named route like blog_category_path()
match "blog/category/:category", :controller => "blog", :action => "category", :as => :blog_category
3) Create the erb or haml view for categories

rugbert
Mar 26, 2003
yea, fuck you

NotShadowStar posted:

Easiest
1) Make a category method on your blog controller
code:
def category
  @posts = Post.where(:category => params[:category])
end
2) Create a route
code:
#the :as parameter creates a named route like blog_category_path()
match "blog/category/:category", :controller => "blog", :action => "category", :as => :blog_category
3) Create the erb or haml view for categories

coool. Im using rails3 tho, so that match would be

code:
match "/blog/category/:category" => "blog#category", :path => "/blog/ something or other
right? and then I could use the same link_to?

NotShadowStar
Sep 20, 2000
Er, I got the route syntax a bit wrong. You're right as in it needs to be a hash, and I generally use the more verbose, older :controller :action syntax but the new way it would look like

code:
match "/blog/category/:category" => "blog#category", :as => :blog_category
Doing :path => :blog will do wacky things because you're likely already mapping /blog to "blog#index". It sounds like you want the URL to be /blog?category=something but you don't actually want to do that. It'll make the index action in your blog controller too complicated, and the URLs aren't as nice. By making a separate method the URLs are nicer as it'll be /blog/category/something and you don't pollute the index method with logic.

rugbert
Mar 26, 2003
yea, fuck you

NotShadowStar posted:

Er, I got the route syntax a bit wrong. You're right as in it needs to be a hash, and I generally use the more verbose, older :controller :action syntax but the new way it would look like

code:
match "/blog/category/:category" => "blog#category", :as => :blog_category
Doing :path => :blog will do wacky things because you're likely already mapping /blog to "blog#index". It sounds like you want the URL to be /blog?category=something but you don't actually want to do that. It'll make the index action in your blog controller too complicated, and the URLs aren't as nice. By making a separate method the URLs are nicer as it'll be /blog/category/something and you don't pollute the index method with logic.

ok so I have this in my routes
code:
  match "/blog/category/:category" => "blogs#category", :as => "blog_category"
and here is my link_to

code:
 blog_category_path(params[:category => category_name])
but it's breaking, giving me:
code:
No route matches {:action=>"category", :controller=>"blogs"}
also - I have a resource for the rest of the blog mapped as
code:
  resources :blogs, :only => [:index, :show], :path => "/blog"  
dont know if that fucks things up

NotShadowStar
Sep 20, 2000
code:
resources :blogs, :only => [:index, :show], :path => "/blog" 
Why do you have it like this?

You should probably rename the controller to 'posts' or 'articles' or some such to be less confusing when you're naming things.

rugbert
Mar 26, 2003
yea, fuck you

NotShadowStar posted:

code:
resources :blogs, :only => [:index, :show], :path => "/blog" 
Why do you have it like this?

You should probably rename the controller to 'posts' or 'articles' or some such to be less confusing when you're naming things.

Thats just how my boss (who wants me to to learn more RoR) taught me. That route just maps out the only the index of the blog and the individual posts.

Are you saying I should make a separate controller for the filtered posts?

NotShadowStar
Sep 20, 2000
Okay, Rails is very heavy on English language semantics, in part because it very much wants you to do REST, and a large part of the idea of REST matching the idea of English verbs and nouns to application actions.

So in what you provided you have a resource named 'blogs'. If you think about this in English, what you are saying is that resource accesses many different blogs. When you're writing your application in Ruby, you write constructions like blogs_path. This doesn't make sense, because that resource isn't accessing different blogs. What is is accessing is different posts or articles.

Now if you rename your controller to posts or articles, it makes much much more sense in the English language, and a lot of the confusion goes away just because you're dealing with something you know.

If you're following you're likely thinking "okay, but the controller and model are named the same". And typically, when you're doing REST and the models are simple, you're exactly correct. There's nothing wrong with that. It actually makes things logically simpler in your mind if you don't think about it. An article controller controls... articles!

So, first thing, rename your controller to something that it actually represents, like posts or articles. Then get rid of the weird :as. You just want to do
code:
resources :posts
Now if you want the root url of the application to be the posts, you just say that
code:
root :to => 'posts#index'
Lastly, why :only? I'm going to guess you have a separate admin controller. Don't do that, what you want to do is protect actions on the posts controller; but we'll get to that later.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
In general you are going to want to think about it with regard to what types of objects you are working. Each object if left to its devices will be listed, shown, created, updated, and destroyed. So, for instance in my application to log a user in, I have a users controller, sessions controller, confirmations controller, and a passwords controller.

Why?

Because I want to be able to list, show, create, update, destroy+ (many) different users. I want to create, destroy sessions (login and out). I want to create confirmations (in case a user has to manually request their welcome email because it wasn't received or whatever). I want to create forgotten password retrievals (in case a user has to request a password reset to get back into their account).

Each of those is a object, which is what we are trying to sort of steer our users to interact with. It makes everything very easy when you think about it like this. It's like shaving huge amounts of weight worth of memory work you would have to do, off of yourself. Because the functionality is so explicit, it's all just named pretty much exactly what it's for.

Then later on, if you know Rail's "way" and the way it likes to do things you'll begin to find more and more that it does those things without you telling it to. As long as you use REST. In fact you might have to tell Rails not to do quite a lot of the things it does. Come to think of it this is a good time to bring up how annoying I am finding it is that I declare all the fields I want the user to have accessible in the model, instead of the controller.

Sometimes I want only certain fields only accessible depending on who the user is, where they are accessing methods from. Or whether the fields are being accessed through a relation.

Is it possible to move attr_accessible functionality to the controller?

NotShadowStar
Sep 20, 2000

Nolgthorn posted:

Is it possible to move attr_accessible functionality to the controller?

Think about this for a second. You're trying to make a case where the a model association is accessible through another model in a controller.

I don't think you quite understand what attr_accessible does. It does not expose model fields as being accessible. It makes the fields you specify fields updatable through mass assignment through another model. Ex:

code:
class Attachment < ActiveRecord::Base
 belongs_to :comment
end

class Comment < ActiveRecord::Base
 has_many :attachments
 belongs_to :post
end
Say you wanted to create comments and attachments in one fell step instead of iterating over arrays. This is really important with complex forms, because that would be a lot of iteration and very very slow and error-prone. It would be something like

code:
@post = Post.where(params[:id].first
params[:comments].each do |field, value|
 if k == :attachment
  value.each do |attachment_name, attachment_value|
   #handle attachment data
  end
 else
  #handle comment fields
  end
end
[code]

That just sucks.  Instead Rails came up with a way to do it all in one fell swoop.  If you use fields_for in your forms, Rails will parse the entire form as a nested hash in the parameters[] that you can use

[code]
@post = Post.where(params[:id].first
@post.update_attributes params[:post]
@post.save
However it's easy to see this can be a very dangerous operation. Simple form manipulation and poking around and someone can use mass-assignment to save fields that form wasn't supposed to. So you have to be explicit in what fields can be saved through mass assignment, and that's exactly what attr_accessible does.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
That's not what I am talking about.

I know, all of that.

I mean what I want to do is restrict the fields that are accessible, further than in the model, from the controller when performing mass assignment from certain actions or controllers which may access the same model.

rugbert
Mar 26, 2003
yea, fuck you
Ah, Ok! Yea that makes perfect sense.

So what Ive done is namespaced my blog to /blog and changed the model to blog_posts. I havent tested the show view yet but categories work now. Thanks! Ill keep these naming conventions in mind.


Another question -

Im learning RoR by making a new site for my tattoo artist. Its a really simple site, has a blog, a page for his tattoos, one for his art, a store (has_many products) and a contact page. Well, someone in the gallery he works at asked me to make a site for the entire gallery now. I want to keep the format exactly the same, but how easy would it be so that each user who is created has access to their own tattoo/artwork galleries,blog, store,products. So that when they log in they only see these things that belong to them.

God that made no sense. Sorry, no sleep last night.

But yea, would I do something in each model like authenticating a user? Or would I created a new field in each model for user and have the controller find blogs/tattoos/whatever by user? RoR is pretty smart so Im assuming theres a way to do this in the models.

NotShadowStar
Sep 20, 2000
Model-level authentication is very rare and almost unheard of. In general you protect resources on the controller. Always think of controllers as the gateway to models, and the models just do their business, so you want to protect the gateway.

Think of it this way. If you're in a larger site and you put a bunch of protection on the models, and you start working with the models directly (say in the console) it'll be a world of hurt.

As for authentication, don't roll your own. You'll get it wrong and screw it up and be insecure. There are tons and tons of very nice authentication systems for Rails. The hottest and latest is Devise. Railscasts has something on it, though it's slightly out of date.

rugbert
Mar 26, 2003
yea, fuck you
Yea, Im using devise to login right now. Super easy. I was just looking for a really easy way to to use the existing site but give each user their own blog/tattoo gallery/store.

edit - DUH, I can just do user > has_one > gallery and each gallery belongs to one user right?

rugbert fucked around with this message at 00:10 on Jan 8, 2011

Sub Par
Jul 18, 2001


Dinosaur Gum
I have an idea for an app I'd like to build, and from what I understand, Rails would be a good framework for it and I've been wanting to learn what all this Rails excitement is about, so I'm going to give it a shot. I have some crappy hosting with MySQL and Rails, but all I see in this thread is stuff about Heroku. So I went to look at pricing... but I don't know jack about what a "dyno" or a "worker" is, how much I might use, or whatever.

This is a simple little app (dinky CRM type thing) for me to gently caress around with and learn rails and possibly get something accomplished. It will just be me using it, low traffic and stuff. The lowest settings on the Heroku pricing page give me $36/month which I don't really want to shell out considering this is just for fun. Should I just install the Rails package on my crappy hosting I've already paid for and go that way, or is that Heroku estimate high for what I'd actually be using? Any suggestions? Thanks.

Edit: after re-reading with my comprehension hat on, it looks like I don't need any Workers and it will be pretty much free for me, since Dyno #1 is free. And I don't really care about performance right now. Sorry for the dumb question.

Sub Par fucked around with this message at 23:11 on Jan 7, 2011

Boner Wad
Nov 16, 2003
Total Rails newb. I've done stuff with other MVC's but this is confusing.

So I have a controller that sets a string variable, like @cocks. When in the view erb, I want to output that variable. It's always nil. I thought I'd add in resources :cocks into the route.rb file, but that didn't seem to help. Any other suggestions?

Additionally, if I'm implementing a form, should I just write it in HTML or is there a Rails way of making a form and POST/GETing it to an action?

BrokenDynasty
Dec 25, 2003

Boner Wad posted:

Total Rails newb. I've done stuff with other MVC's but this is confusing.

So I have a controller that sets a string variable, like @cocks. When in the view erb, I want to output that variable. It's always nil. I thought I'd add in resources :cocks into the route.rb file, but that didn't seem to help. Any other suggestions?

Additionally, if I'm implementing a form, should I just write it in HTML or is there a Rails way of making a form and POST/GETing it to an action?

Do yourself a huge favor and read some of the guides: http://guides.rubyonrails.org/. It will help you with your form building.

NotShadowStar
Sep 20, 2000
Alternately buy the best book there is

(Really wish pragmatic programmers had affiliate linking)

Hammertime
May 21, 2003
stop

NotShadowStar posted:

Alternately buy the best book there is

(Really wish pragmatic programmers had affiliate linking)

Quoting this because this book is simply the best way to do it. I used it, all my rails devs used it. It's efficient and fun.

Bob Morales
Aug 18, 2006


Just wear the fucking mask, Bob

I don't care how many people I probably infected with COVID-19 while refusing to wear a mask, my comfort is far more important than the health and safety of everyone around me!

If you guys had put this book on the first page, I wouldn't have bought it today, since I found it is free online after I came home! Oh well, the author gets a sale and a couple bucks, and I really needed a book this weekend.

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

Sub Par
Jul 18, 2001


Dinosaur Gum
Ok, so I'm on Windows (Vista) on my laptop, and everything I read says that it is best to develop on Linux. So I've read about using Linux via Virtual PC 2007, and gotten that working, but I can't seem to get Ubuntu 10.10 to install all the way - it hangs halfway through. It's starting to piss me off, so now I'm about to try Gentoo, but is it really a bad idea to develop on Windows? Is all the trouble I'm going through to get this going gonna be worth it?

Bob Morales
Aug 18, 2006


Just wear the fucking mask, Bob

I don't care how many people I probably infected with COVID-19 while refusing to wear a mask, my comfort is far more important than the health and safety of everyone around me!

Sub Par posted:

Ok, so I'm on Windows (Vista) on my laptop, and everything I read says that it is best to develop on Linux. So I've read about using Linux via Virtual PC 2007, and gotten that working, but I can't seem to get Ubuntu 10.10 to install all the way - it hangs halfway through. It's starting to piss me off, so now I'm about to try Gentoo, but is it really a bad idea to develop on Windows? Is all the trouble I'm going through to get this going gonna be worth it?

Just use Windows for a while. So far it seems like everyone who uses Ruby has a Mac... I am up and running on Fedora 14, haven't tried my MacBook Pro yet.

VirtualPC is windows-only but apparently this will let you run Ubuntu:

http://www.sysprobs.com/install-ubuntu-1010-virtual-pc-2007-windows-7-host

Alternatively, try VirtualBox.

The Journey Fraternity
Nov 25, 2003



I found this on the ground!
VirtualBox is pretty nice, I'd toss my vote in for that too.

NotShadowStar
Sep 20, 2000

Sub Par posted:

Ok, so I'm on Windows (Vista) on my laptop, and everything I read says that it is best to develop on Linux. So I've read about using Linux via Virtual PC 2007, and gotten that working, but I can't seem to get Ubuntu 10.10 to install all the way - it hangs halfway through. It's starting to piss me off, so now I'm about to try Gentoo, but is it really a bad idea to develop on Windows? Is all the trouble I'm going through to get this going gonna be worth it?

Ruby on Windows is still a hellaciously painful ordeal. Last time I did it I resorted to rvm under Cygwin and it was P A I N F U L L Y slow. So much I went 'gently caress it I'm going Ubuntu'.

Most of the problem comes from the lack of a decent GCC on Windows, lots of the Ruby C-based extensions, like mysql and sqlite use GCC.

8ender
Sep 24, 2003

clown is watching you sleep

NotShadowStar posted:

Alternately buy the best book there is

(Really wish pragmatic programmers had affiliate linking)

Also if you're not fluent with Ruby then the really fantastic Why's poignant guide to Ruby is also a great place to start:

http://mislav.uniqpath.com/poignant-guide/

Even as a developer who knew a box full of languages already I enjoyed the hell out of this. It really got me off to a good start.

Sub Par
Jul 18, 2001


Dinosaur Gum
Thanks guys for all your help. After trying repeatedly to install Ubuntu using Virtual PC and failing, I just installed gVim, Git, and the whole bit on Windows. While slow, it seems to be working and I'm up and running on Heroku. Despite all the trouble... this is awesome! Like, two commands and I'm deployed? Love it.

rugbert
Mar 26, 2003
yea, fuck you

Sub Par posted:

Thanks guys for all your help. After trying repeatedly to install Ubuntu using Virtual PC and failing, I just installed gVim, Git, and the whole bit on Windows. While slow, it seems to be working and I'm up and running on Heroku. Despite all the trouble... this is awesome! Like, two commands and I'm deployed? Love it.

You mean Virtual BOX right? I thought installation was a breeze, what kind of problems did you have?


Also - Can I change my project name? I want to reuse this project for a couple different sites so I should probably change the project name.

Sub Par
Jul 18, 2001


Dinosaur Gum

rugbert posted:

You mean Virtual BOX right? I thought installation was a breeze, what kind of problems did you have?


Also - Can I change my project name? I want to reuse this project for a couple different sites so I should probably change the project name.

No, Virtual PC (a Microsoft product). Installation just stopped when the progress bar was about 60% complete. I don't know why. I tried it several times, and even let it sit for several hours just in case it wasn't stopped but just taking a while. No dice.

Things seem to work well in Windows. Installed gVim, Git, etc and am working through one of the tutorials posted upthread just fine and dandy.

rugbert
Mar 26, 2003
yea, fuck you

Sub Par posted:

No, Virtual PC (a Microsoft product). Installation just stopped when the progress bar was about 60% complete. I don't know why. I tried it several times, and even let it sit for several hours just in case it wasn't stopped but just taking a while. No dice.

Things seem to work well in Windows. Installed gVim, Git, etc and am working through one of the tutorials posted upthread just fine and dandy.

Ive never used Virtual PC but Virtual Box is loving awesome. Its really snappy. Try that, its free.

Its just a hell of a lot easier doing any web dev on a *nix system. I do miss textpad++ tho :/

Obsurveyor
Jan 10, 2003

Sub Par posted:

No, Virtual PC (a Microsoft product). Installation just stopped when the progress bar was about 60% complete. I don't know why. I tried it several times, and even let it sit for several hours just in case it wasn't stopped but just taking a while. No dice.
Virtual PC is oddly unstable for the virtualized OS when running Ubuntu. It really annoys me because it feels like something Microsoft would do on purpose. I had to start using VMWare because of this.

Cock Democracy
Jan 1, 2003

Now that is the finest piece of chilean sea bass I have ever smelled

Obsurveyor posted:

Virtual PC is oddly unstable for the virtualized OS when running Ubuntu. It really annoys me because it feels like something Microsoft would do on purpose. I had to start using VMWare because of this.

This reminds me of back in the Windows 3.1 days, I installed WordPerfect and it would give me these kinds of errors constantly. I thought for years that it was an MS conspiracy to get you to buy Word.

Obsurveyor
Jan 10, 2003

Cock Democracy posted:

This reminds me of back in the Windows 3.1 days, I installed WordPerfect and it would give me these kinds of errors constantly. I thought for years that it was an MS conspiracy to get you to buy Word.
I am not a Microsoft hater or anything at all. It is my primary OS and I use Visual Studio for development(thank god for viemu), I really could not be more of a Windows guy these days. Whenever I would try to use Ubuntu under Virtual PC, it would get random kernel panics and memory errors.

Currently working on a FreeBSD machine for migrating the company's website over to Rails. :woop:

Adbot
ADBOT LOVES YOU

rugbert
Mar 26, 2003
yea, fuck you
how doe reject work?

Uve got a model PageContent with a field called type.

Its its controller Im trying to get all PageContent entries except ones that have the type of BlogPost.

I tried
@pages = PageContent.all.reject{|p| p.type == 'BlogPost'}

But thats not doing poo poo

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