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
Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Plastic Jesus posted:

What's the correct RESTful way to do a site-wide search? That is, the search itself will cover multiple models and I'm not quite sure what the "right" route is. Should it just be application#search? That seems strange.

For a generic search, I'd probably make the controller "Searches" or "SiteSearch", talking to a "SiteSearch" model that handles interaction with ThinkingShinx or whatever engine you end up using.

Adbot
ADBOT LOVES YOU

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Plastic Jesus posted:

I created a controller and view for search, but I don't see why it needs a model. I could be wrong about this, as I'm usually wrong about these things.

Putting logic in a model (models don't have to be ActiveRecord::Base children; they can be a plain old object too) means you can unit test it easier. Searches and fancy queries are a good example, because sometimes (especially pre-arel) there's a bunch of logic used to filter, sort, and join on different columns. You want to be able to test all this stuff and make sure it works without having to pick apart HTML to see if it did the right thing.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Bob Morales posted:

Ideally I'd like one new post controller and have it decide things based on what I pass to it, I guess I just don't know how to pass it.
code:
resources :topics do
  resources :posts
end
That would give you /topic/new for posting a new topic, /topic/420/post/new for replying to a topic, and you get /topic/420/post/new?quote=888 for free.

You should probably split it up into the TopicsController and PostsController, and even if a Topic is just a Post with no parent, I'd be tempted to make a Topic model just so you can have a nice place for all the topic-finding methods.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Obsurveyor posted:

I am about at my breaking point with using Devise.

You might not want to hear this, but ripping Devise out of a project that used it was one of the best things I've ever done for productivity.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

A MIRACLE posted:

Thanks. Is there a reason the changes I make on a views/ file take some time to propagate (as opposed to showing the results instantly)?

Are you editing on the live server running in production mode? If so, don't do that; edit locally in development mode, use version control, and a deployment tool. PHP amateur hour poo poo doesn't fly in Rails.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

8ender posted:

I ended up creating a temp directory in my rails public folder, creating a file for export, writing the xlsx and streaming it with send_file, then using FileUtils to manually delete it afterwards. Its a kludge but it works.

If you're using send_file, you probably don't need to put it in $APP/public/, you could get away with $APP/tmp or /tmp/application_name.

If generating the xlsx is a slow task and you're not on Heroku or Windows, I'd probably use resque to move the xlsx generation out of the web request.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

rugbert posted:

Can you use multiple accounts on heroku from the same computer? I dont like the idea of hosting a bunch of client sites on my heroku account. Sometimes I want to just push it off on them after Im done building so I dont have to deal with them anymore.

Make a new account for the client site, grant your account permissions. As part of the client handoff, make sure they log in, change and document the credentials, and remove your permissions.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Obsurveyor posted:

Does anyone understand how before_filters work in Rails 3? I have been struggling with trying to secure js/json access to my app using the auth filters I already have setup to avoid code duplication. before_filter is supposed to be an alias for append_before_filter which implies that it is not messing with filters created beforehand, thus the word "append". However, if you do something like:

code:
before_filter :authenticate
before_filter :content_editor?
#append_before_filter :authenticate, :only => [:show]

...
private

  def authenticate
    puts "Authenticating"
  end

  def content_editor?
    puts "Are you a content editor?"
  end
Everything works great, all actions run both filters, as expected. However, if you uncomment the append_before_filter line, authenticate stops being called for all actions and is only called for :show now.

This seems broken to me.

Why are you trying to run the same before_filter multiple times?

code:
class DicksController < ApplicationController
  before_filter :require_login

  def require_login
    require_http_session || require_oauth_session
  end

  def require_http_session
    return false unless current_user
  end

  def current_user
    @current_user ||= User.find(session[:user_id])
  end
end

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Obsurveyor posted:

The actual filter would not run multiple times in a real scenario, that was just to show the Rails behavior. This is exactly what I wanted to do earlier:

code:
before_filter :authenticate, :except => [:show, :list]
before_filter :content_editor, :except => [:show, :list]
before_filter :authenticate, :only => [:list], :if => :request_js?
before_filter :content_editor, :only => [:list], :if => :request_js?
So you see, it only runs once for any request. I need to block access to a specific action's js/json format if the user is not a content editor. This does not actually work though.
Why would you need to block a specific action for a specific format? If the js version of the action does something wildly different, it's not the same action.

But answering the question you asked instead of the question you should be asking, this is passable I guess:
code:
before_filter :authenticate, :except=>[:show, :list]
before_filter :authenticate_for_show, :only=>:show
before_filter :authenticate_for_list, :only=>:list
The easiest thing might just be to override authenticate in that controller and check conditions before calling super.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

rugbert posted:

Ok I made a new account to test this out. Where can I grant my account permissions? I guess what I need to do is create an app on the new account, and then give my account the ability to collaborate? Is there a way to do that from my computer? Because my computer is tied to my account, should I use a VM?
From the command-line heroku tool:
code:
sharing:add <email>                        # add a collaborator
sharing:remove <email>                     # remove a collaborator
sharing:transfer <email>                   # transfers the app ownership

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

plasticbugs posted:

Thanks for your help! I'm reading up on memoization right now.

If you're on Rails 3 (or are otherwise pulling in activesupport 3), you can get a bunch of exrta tools (cache flushing, priming, for free by using the Memoizable module:
code:
class Thingy
  extend ActiveSupport::Memoizable
  
  def slow_thing
    1_000_000.times {…}
  end
  memoize :slow_thing
end
See http://api.rubyonrails.org/classes/ActiveSupport/Memoizable.html and http://api.rubyonrails.org/classes/ActiveSupport/Memoizable/InstanceMethods.html

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

rugbert posted:

Awesome thanks, Im not seeing anything for another issue Im having where it takes a minute for my app to load so Im assuming thats normal.

Yeah, Heroku doesn't run every app all the time, they're spawned on demand.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

jetviper21 posted:

This is also the easy way and non elegant way.

code:
@blog_posts = BlogPost.where("created_at < ?", Time.now)
Use a named scope, and put it on the model so you can test it.
code:
class BlogPost < ActiveRecord::Base
  scope :before_today, where('created_at < ?', Time.now)
end
And then invoke with:
code:
BlogPost.before_today

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

skidooer posted:

Good advice, but you'll want to put that in a lambda, otherwise Time.now will be evaluated when the model loads and will not increment with the clock.
code:
scope :before_today, lambda { where('created_at < ?', Time.now) }

Good call, but your tests should cover that :)

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

NotShadowStar posted:

Nope, and actually you shouldn't be using scopes anyway.

http://www.railway.at/2010/03/09/named-scopes-are-dead/

And according to Aaron Patterson, lambdas are much slower than method calls anyway. (http://confreaks.net/videos/427-rubyconf2010-zomg-why-is-this-code-so-slow) around 28:00.

But everyone should watch the whole thing.

I think that post is based on some allergy to the same-line lambda syntax. That they're still in 3.1, not throwing a deprecation warning, shorter, easier to read, and easier to test is a good indicator that they're still a best practice.

The lambda-vs-method-call thing is a bit of a red herring; the block isn't run for every record in the set, it's run once to build the association. I'd rather lose microbenchmarks and have declarative scopes than the reverse.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

NotShadowStar posted:

I still don't understand what the point of this is. The only use-case that I see is 37s has cross-app dependencies, so that makes it easy. Most people don't have this, so the Passenger Preference Pane is just fine.

I think it's just that making a symlink is less work than firing up the prefpane, waiting for it to restart in 32-bit mode, typing a password, and dragging a folder in.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

NotShadowStar posted:

That's some serious first world problem.

Also 'rails server' is also just fine for development.

Every problem in software and computing is a first world problem, and "just fine" isn't when "fantastic" is available and free.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

plasticbugs posted:

Thanks for the tips. I did want to obfuscate the Message ID somehow and I probably will soon to avoid the expensive lookup by message_url operation.

If it's indexed in the database it shouldn't be expensive.

If you still want to have something obfuscated but that doesn't look like you're just incrementing, can I recommend https://github.com/bkerley/have-code ? It probably works just fine with ActiveRecord 3.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

plasticbugs posted:

One more question popped up. I want to limit users to creating 5 total items. Items belong to Users.
Can I run a validation inside my Item model that won't allow a user to create a sixth item by checking self.user.items.count < 6

In pseudo-ish code (obviously, this doesn't work)

class Item
validates_numericality_of self.user.items.count, :less_than => 6
end

The best way to do that seems to be to make a ActiveModel::Validator class inside the Item:
code:
class Item
  class ItemCountValidator < ActiveModel::Validator
    # implementation left as an exercise for the reader
  end

  validates_with ItemCountValidator
end

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Nolgthorn posted:

I love Haml and Sass, to the extent that I think that support should be implemented natively in all browsers. Whenever I don't get to use Haml or Sass I find myself annoyed, like I need to cross a stream but before I do I'm told that I am not allowed to use the big piece of plywood that has been laid down over the stream for me to cross with.

From what I understand coffeescript is the same thing, if that's true then I'm sure I'll get used to it as long as it doesn't change the code I am writing.

HAML and SASS are fine the way they are, and unless you have to be observed hand-writing invalid HTML for a class project or something, you can use them on static site projects just fine.

CoffeeScript is even better than HAML & SASS just because JavaScript is more powerful and has more space to be annoying.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Nolgthorn posted:

When you say Haml and Sass can be used for static site projects, you still have to compile those pages.

I'm dreaming of the day you can just use them, send the haml ans sass to browsers the way they are.
This is easy if you're using an automated deployment setup. https://github.com/bkerley/design-miami-challenge-apr-2011/blob/master/Rakefile uses the charleston gem to run the generators, and pushes the gh-pages branch to GitHub Pages for hosting.

The big benefit is I can set my editor to run rake on save, or run rake output:push to build and publish the pages in one quick step.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

skidooer posted:

I look forward to the day the browser is just a virtual machine and the HTML engine is a downloadable component.

The downside is that third party tools, such as web crawlers, would be much more difficult to build. With that said, we're pretty much already at that point: See NSS's post as an example. We're a lot of things in Javascript already to simulate what a full virtual machine should be doing. Why not just go all the way?

Do you want to have the security history, compatibility, and accessibility of ActiveX, Flash, or Java applets?

Much of the web stack is focused on providing a way to incrementally implement tools that use it, and any replacements or improvements to it will be just as modular and easy-to-implement.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Bob Morales posted:

The problem is there's a few hundred a day so they get ignored, unless they start repeating. And they're probably things that should be fixed anyway. But they might as well be 'warnings'.

So quit being a baby about it: every morning, pick one, write a test, fix it, deploy it.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Trabisnikof posted:

Yeah, I have no idea how to get my shop to use tests.

So quit and go somewhere that does it right. There's a huge demand for Rails developers who want to do things the right way.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

NotShadowStar posted:

Where oh god I want to leave the midwest frozen wasteland where people can't stop using PHP

PM me if you're serious, at least one of my friends is looking for Rails people in Miami; they don't pay for relocation but here's a sample of our January weather:

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug
I worked in a shop like that, where the pressure to deploy anything at all was interfering with my ability to make quality software.

I went to the management and said, "my last day is in two weeks," and haven't looked back. If they won't let you make quality software, they deserve what they get, and you don't deserve to get stuck with it.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

8ender posted:

also this: https://github.com/thoughtbot/high_voltage

is pretty fly if you just need to serve up some static pages easily

I use that just because I can use markdown embedded in haml to make my static pages:
code:
- content_for :title do
  Privacy Policy
.prose
  :markdown
    # Privacy
    
    gurgle [hurgle](http://goatse.info/) tincidunt congue enim, ut porta lorem lacinia consectetur.
    Donec ut libero sed arcu vehicula ultricies a **non tortor.** Lorem ipsum dolor sit amet, consectetur
    adipiscing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a semper `sed`, adipiscing id dolor. 

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

NotShadowStar posted:

Also, if some of your application errors are coming from Google trawling through your site and hitting AJAX only URLs, your AJAX setup is probably incorrect. Essentially you want the inverse of what this document tells you to do.

I'd bet he's using the link_to :remote stuff.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug
Anybody going to RailsConf this week? I'll be at the free Bohconf track Wednesday and Thursday.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

enki42 posted:

I'm there now. Tutorial day was a little dull, looking forward to the keynote today. You should head over to the GitHub meetup on Wednesday, we'll have a beer.

Cool! I'm bonzoesc on Twitter if you have it.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug
I made a thing.



It plugs into a Rack application on Ruby 1.9.2 and allows you to browse the source.

For Rails 3:

Add gem 'cans' to your Gemfile.
Add mount Cans::Application.new, :at=>'/cans' to your config/routes.rb

Browse to /cans/browser for the pretty backbone.js-based browser.
Browse to /cans/ for the less pretty HTML-only views.

Source is at http://github.com/bkerley/cans

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Pardot posted:

That's cool. Were you inspired by seaside? If not, check out Seaside.

The presentation I made for lightning talks at Rubyconf 2010 actually had a screenshot from Squeak in it :)

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.

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 ?

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.

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

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?

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.

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).

Adbot
ADBOT LOVES YOU

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([…])

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