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
Lamont Cranston
Sep 1, 2006

how do i shot foam

MrSaturn posted:

I've got another question

What do your routes look like for the blogposts controller? It looks like you have it set up for /blogposts/:id, which would explain why /blogposts/rss would screw up (it's looking for a post with id of "rss").

Adbot
ADBOT LOVES YOU

Lamont Cranston
Sep 1, 2006

how do i shot foam
OK, I'm trying to wrap my brain around this RESTful stuff, and I think I've got it. I was experimenting with refactoring one of my existing apps to REST, but here's the snag I run into.

For my "user" controller, I have my routes set up like so:
code:
map.connect 'user/:user', :controller => "user", :action => "view"
So I can have URIs like "foobar.com/user/Lamont_Cranston" instead of "foobar.com/user/14525". I can't figure out how to do this in REST with map.resource. I know I could override to_param in my model but I wouldn't like to use :id for anything but the id. Anybody know how I could accomplish this?

Lamont Cranston
Sep 1, 2006

how do i shot foam

SeventySeven posted:

Just a constant, nothing fancy.

I used environment.rb to store a constant with my Google API key, that might work for you.

Lamont Cranston
Sep 1, 2006

how do i shot foam
I wonder if anyone could help me out with an issue I'm having.

I've just deployed an app using restful_authentication on edge rails (2.3.0) and it works perfectly in my development environment. I deployed it to my web server in production however, and it seemed that the session was not persisting between requests. I set up some loggers inside the current_user= method in AuthenticatedSystem and I could see that the session variable was being set, but then when the app redirected to the page that needed authentication, logged_in? returned false and there was nothing in the session. I could see that it set a cookie however.

I tried changing it to active_record_store, which worked, but now every few requests there's a pause of about 5 seconds before the page loads.

Does this ring any bells for anyone? I can't figure it out and Google's been worthless. I can provide more details upon request. Thanks.

Lamont Cranston
Sep 1, 2006

how do i shot foam
Anyone know how I can dynamically get a list of the actions in a controller? From the console, I can do this:
code:
FooController.public_instance_methods(false)
#=> ["index", "another_action", "whatever"]
But from inside the controller, putting
code:
self.public_instance_methods(false)
yields an empty array. Any idea why or how I can get the above behavior within a controller?

Lamont Cranston
Sep 1, 2006

how do i shot foam

skidooer posted:

Call the method after your methods have been defined. i.e.
code:
class FooController < ApplicationController
  public_instance_methods(false) # => []

  def index
  end

  public_instance_methods(false) # => ["index"]
end

Hah wow, that was way simpler than I thought. Thanks!

Lamont Cranston
Sep 1, 2006

how do i shot foam
Well, after getting past the above problem, I finally finished up / extracted a plugin for search engine XML Sitemaps. There's one out there already but I didn't really like how it was installed and set up, I wanted something where I could just stick a method in my controller and have it be mapped. I have no clue if this will be useful for anybody else, but here it is:

http://github.com/tylercunnion/sitemap_xml/tree/master

I'll gladly accept any suggestions/patches. Let me know if you find it useful!

Lamont Cranston
Sep 1, 2006

how do i shot foam
I'm trying to implement custom 404 pages using method_missing in my ApplicationController. This code:
code:
  def method_missing(methodname, *args)
    begin
      super
    rescue ActionView::MissingTemplate
      render 'error/index', :status => 404
    end
  end
should do the trick but it throws "ArgumentError (no id given)" when it calls super. I know this can happen if I modify the value of "methodname" but I don't. Any ideas?

Lamont Cranston
Sep 1, 2006

how do i shot foam

NotShadowStar posted:

Leaving in one minute but I don't know if that will even work, since you got to method_missing through a render with a missing template (explicit or implicit) so you'll get a double render error when you get that far. I think. You probably want to look at rescue_action_in_public

Cool. I just changed the code to
code:
  def method_missing(methodname, *args)
    rescue
      render 'error/index', :status => 404
  end
to see if it would work and it does. I'll look into this though, so I'm not messing with method_missing voodoo if I don't have to be.

Lamont Cranston
Sep 1, 2006

how do i shot foam

Myrddin Emrys posted:

Total newbie here, just picked up my first RoR book and tried my hand at installing it on Linux.

Dear God, I have the anti-Linux touch. Give me a Linux box, any box, and I will crash it within minutes doing normal things.

Installation of ruby 1.9 was a success, as was gems. Installation of rails failed, because as it turns out OH WAIT ruby wasn't installed. Synaptic and apt-get both reported that ruby was installed, but when I checked the location it spit out, there was nothing there. No folder, no files, nothing. It lied to me :(

So, new distro, and here we go again.

Just as a suggestion (and someone please correct me if I'm out of date here), you should stick with ruby 1.8.7 for now. Rails is quickly being converted for use on 1.9 but it's not quite there yet.

Lamont Cranston
Sep 1, 2006

how do i shot foam
I've got a bit of a problem getting rails to use the right version of Ruby. My hosting provider has 1.8.6 living in /usr/bin, while I have 1.8.7 in /usr/local/bin. When I run the ruby command I get 1.8.7 but Rails has been using 1.8.6 for some reason. Any idea where this gets set or if there's an environment variable I can set up to get it looking in the right place? I'm running Thin behind Apache.

ed: I get this error when I try to run script/console, if it helps:
code:
/usr/local/lib/ruby/site_ruby/1.8/rbconfig.rb:6: ruby lib version (1.8.6) doesn't match executable version (1.8.7) (RuntimeError)
	from /usr/local/lib/ruby/site_ruby/1.8/rubygems.rb:62:in `require'
	from /usr/local/lib/ruby/site_ruby/1.8/rubygems.rb:62
	from ./script/../config/../vendor/rails/railties/lib/rails/vendor_gem_source_index.rb:1:in `require'
	from ./script/../config/../vendor/rails/railties/lib/rails/vendor_gem_source_index.rb:1
	from ./script/../config/../vendor/rails/railties/lib/rails/gem_dependency.rb:1:in `require'
	from ./script/../config/../vendor/rails/railties/lib/rails/gem_dependency.rb:1
	from ./script/../config/../vendor/rails/railties/lib/initializer.rb:10:in `require'
	from ./script/../config/../vendor/rails/railties/lib/initializer.rb:10
	from ./script/../config/boot.rb:45:in `require'
	from ./script/../config/boot.rb:45:in `load_initializer'
	from ./script/../config/boot.rb:38:in `run'
	from ./script/../config/boot.rb:11:in `boot!'
	from ./script/../config/boot.rb:109
	from script/console:2:in `require'
	from script/console:2

Lamont Cranston fucked around with this message at 21:52 on Jan 13, 2010

Lamont Cranston
Sep 1, 2006

how do i shot foam
Looks like the problem came from installing 1.8.7 overtop of 1.8.6. I removed my /usr/local/lib/ruby and reinstalled and everything seems to be going well.

Lamont Cranston
Sep 1, 2006

how do i shot foam
Since this is more or less the Ruby thread, I'll ask this here -
I'm using RSpec but I'm pretty new to it. I'm writing a web crawler and I want to set up a test to ensure that any page is only downloaded once. I have my Crawler class send an update message to my Observer class every time it downloads a page with the response and URI objects as arguments.

My test looks like this:
code:
          uri = URI.parse('http://localhost:12000')
          @obs.should_receive(:update).with(kind_of(Net::HTTPResponse), uri + '/page5.html').once
          @crawler.crawl(uri)
This passes even though I know that page5.html is downloaded twice. If I change .once to .twice, it also passes. If I change to 3 times, I get this:
code:
Mock "observer" received :update with unexpected arguments
  expected: (#<Spec::Mocks::ArgumentMatchers::KindOf:0x1010615d8 @klass=Net::HTTPResponse>, #<URI::HTTP:0x1010600e8 URL:[url]http://localhost:12000/page5.html[/url]>)
       got: ([#<Net::HTTPOK 200 OK  readbody=true>, #<URI::HTTP:0x10105ef68 URL:[url]http://localhost:12000/[/url]>], 
          [#<Net::HTTPOK 200 OK  readbody=true>, #<URI::HTTP:0x101038160 URL:[url]http://localhost:12000/page2.html[/url]>], 
          [#<Net::HTTPOK 200 OK  readbody=true>, #<URI::HTTP:0x101033110 URL:[url]http://localhost:12000/page3.html[/url]>], 
          [#<Net::HTTPNotFound 404 Not Found  readbody=true>, #<URI::HTTP:0x1005b4540 URL:[url]http://localhost:12000/page4.html[/url]>])
Anybody have any idea what I'm doing wrong?

Lamont Cranston fucked around with this message at 23:31 on Jan 24, 2010

Lamont Cranston
Sep 1, 2006

how do i shot foam

Operation Atlas posted:

It's hard to tell without looking at the code in your app, but I think you're passing every page url in an array each time you talk to the observer. Each time you hit a new page, the array grows and so does the list of pages passed to the observer. Because of the way RSpec does "with", as long as the page is in that array it will pass.

It just passes the URI object, no array. I managed to get it to (correctly) fail when I change to:
code:
@obs.should_receive(:update).with(kind_of(Net::HTTPResponse), uri + '/page5.html').once
@obs.should_not_receive(:update).with(kind_of(Net::HTTPResponse), uri + '/page5.html')
but this doesn't seem like it's how it should have to work.

Lamont Cranston
Sep 1, 2006

how do i shot foam
http://github.com/tylercunnion/crawler/blob/master/lib/crawler/webcrawler.rb

It's not passing an array, have a look for yourselves.

At any rate, I think the problem I'm having has to do with what they discuss in this ticket:
https://rspec.lighthouseapp.com/projects/5645/tickets/618-exactlyntimes-incorrectly-failing-for-n-actual

I stub the update method onto my observer object, because for the Observable module, observer classes must respond to update. Then, I put an expectation on top of that - and when it's finished, it removes the expectation and reverts back to the stub method - which is why it doesn't catch that the method is being called more than what I specify, but it will catch it when I put the expectation to a high number I know it won't reach.

Anyway, thanks for your help. I guess I'll just have to continue to work around or else figure out something clever.

Lamont Cranston
Sep 1, 2006

how do i shot foam
Holy crap, how had I not heard of Heroku before? This looks amazing.

Lamont Cranston
Sep 1, 2006

how do i shot foam
I'm having a little time zone trouble.

So I get the idea that times stored in the DB are in UTC, and it's the app's responsibility to adjust for local timezones. I've set my timezone as Eastern in application.rb. My form uses a time_select.

So I submit the form with a time of, say, 13:00. My understanding is that it should go into the database as 18:00 UTC (as EST is UTC-5), but it doesn't, it goes in as 13:00 UTC. Is there somewhere else I need to be compensating for this before I send it to the database? What am I doing wrong here?


I had the types set in my schema as time instead of datetime. Changing that fixed it right up.

Lamont Cranston fucked around with this message at 22:57 on Aug 22, 2011

Lamont Cranston
Sep 1, 2006

how do i shot foam
Does anyone know how I can include associated objects in a query according to a scope? I have Companies with many Jobs, but Jobs expire after a certain amount of time, so when I do Company.includes(:jobs) I want to be able to limit what it includes to just active jobs. Is there any way to do this? I already have an 'active' scope on Jobs, and I was hoping I would be able to reuse that, but I'll take anything.

Lamont Cranston
Sep 1, 2006

how do i shot foam

ZanderZ posted:

Can anyone help me better understand methods? I'm trying to write a method for the current user that currently looks like this.

def current_user= (user)
@current_user ||= user_from_remember_token
end

It seems pretty redundant, especially considering the fact that I have a controller for users and a controller for sessions and current_user is defined the same way, in both. It's also in both helpers.

I'm getting a no method error when I try to use <% if current_user?(display_user.info) %> I assume it's having an issue with the method for current_user or is the error in regards to "display_user.info"?

What's a good format for "current user?" I have it set, so it's dependent on cookies, but I'd rather it just assume that "current user" is the user that's currently logged in. Should I be defining it in the users controller or the sessions controller? I'm pretty good at overcomplicating things.

First of all, a method called "current_user=" is a setter, and the body of your method is a getter. Also, "current_user", "current_user=" and "current_user?" are all different methods, that's why you're seeing a method not found error.

Apart from that I don't know enough about the implementation of your authentication system to be able to say. Are you using a gem for authentication? If you are, you probably don't need to do the implementation for current_user yourself.

Lamont Cranston
Sep 1, 2006

how do i shot foam

Physical posted:

code:
class Tweet < ActiveRecord::Base
  
end
What does the ::Base do?

Base is the class' name, ActiveRecord is the module or package, :: is the namespace operator.

Lamont Cranston
Sep 1, 2006

how do i shot foam

Look Around You posted:

That being said, if you want to really make yourself a "better" programmer, I'd recommend learning a functional language like Haskell or Lisp. They're really awesome languages in general, and functional programming is a good way to get a better grasp of recursion (especially considering that you don't really have loops at all!). It's also just good to step out of your comfort zone sometimes. A good book for learning Haskell is Learn You a Haskell for Great Good by fellow goon Bonus. Lisp has a couple good books too, notably SICP and How to Design Programs, which is sort of SICP lite.

Just wanted to say thanks for this. I've always wanted to explore a functional language and I've been working through the Haskell book; fascinating stuff.

Lamont Cranston
Sep 1, 2006

how do i shot foam

Physical posted:

Is there something that I don't know that prevents me from assigning a value to a key in a hash.each loop?

code:
     #ok so we have our list of locations, now find the staff resources that have this id that are used by the dept in the plan
     @plan.departments.each do |dep|
        #loop through the staffings to find staffings with the location we want
        dep.staff.each do |staff|
          #now cross reference this current staffing's.loc_id with the list we have previously
          data.each do |k, v|
            # "location id thing " + staff.location_id.to_s                 
            if k.to_i == staff.location_id.to_i 
              v = Hash.new()
              v[dep.id.to_s] = staff
              %> <%= v.inspect + "data inspect #{data.inspect}"%>     <br /> <br />    <%      
            end                            
          end
        end        
     end
When I inspect the data of v, it looks good. But the inspection on data (the owner of v) shows nothing. What gives?

Just setting v won't do it; you'll have to do data[k] = (your new v).

(Though something tells me you could probably do this with inject instead. I'm not super familiar with the ins and outs but you might want to take a look.)

Lamont Cranston fucked around with this message at 01:05 on Mar 28, 2012

Lamont Cranston
Sep 1, 2006

how do i shot foam

Strong Sauce posted:

inject is essentially a reduce, how is that going to help him here? I am guessing you're referring to mapping?

Well yes, but map returns an array. I was thinking he could do something like
code:
data.inject({}) do |hash, (k,v) | 
    #manipulate v however you want
    hash[k] = v
    hash
end
It at least avoids the problem of modifying the structure as your iterating over it.

Lamont Cranston
Sep 1, 2006

how do i shot foam

Strong Sauce posted:

Ah yes I kept thinking that the object returns as an array of hashes and not a hash. Still your solution doesn't actually modify `data`, it just returns a copy such that data is still not changed.

True, but that's all I was really going for anyway.

Adbot
ADBOT LOVES YOU

Lamont Cranston
Sep 1, 2006

how do i shot foam

Thoom posted:

I'm starting to get really pissed off with Rails' magic.

I'm trying to extend Redcarpet to add a custom markdown tag, in which I'd like to use one of my helpers to generate a link.

code:
module ApplicationHelper
  def link_to_pub(pub, title = nil)
    title ||= pub.to_s

    link_to title, publication_path(pub)
  end

  def redcarpet_render(content)
    @@markdown ||= Redcarpet::Markdown.new(HTMLWithRefs, :autolink => true)
    @@markdown.render(content).html_safe
  end

  class HTMLWithRefs < Redcarpet::Render::SmartyHTML
    def preprocess(document)
      document.gsub!(/\[ref ([a-zA-Z_\-]+)\]/) do |m|
        link_to_pub(m[1])
      end
      document
    end
  end
end
When I call redcarpet_render("[ref bob]"), I get the following exception:

code:
undefined method `link_to_pub' for #<ApplicationHelper::HTMLWithRefs:0x007f8114a6b2a0>
despite link_to_pub being defined in the loving enclosing scope, Rails, you rear end in a top hat. What do I have to do to make link_to_pub visible to HTMLWithRefs?

On a related note, does anyone know in what scope named route helpers (e.g. publication_path()) are defined, and how to break them out of that scope? There is absolutely sweet gently caress all for documentation about where any given method is visible in rails in case you want to use them outside of their original context.

You're trying to treat Ruby like Javascript. You're defining a new class with HTMLWithRefs and nothing outside of that is in scope, regardless of whether it's in the same file.

In any case, Redcarpet cannot see the methods you've defined in the helper file. Those are in their own module (ApplicationHelper) which only gets mixed into the view. You could (I guess) import the ApplicationHelper module into your file, but then your helper method relies upon the link_to method, so you'd have to include whatever module that's in, and so on. You'd be pounding a square peg into a round hole. Better to forget about trying to shoehorn helpers where they weren't meant to go, and just write out the HTML for the link yourself in your preprocess method.

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