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

Fillerbunny posted:

Ruby code:
#polymorphic model
class WikiEntry < ActiveRecord::Base
  belongs_to :wikiable, :polymorphic => true
end

class SomeObject < ActiveRecord::Base
  has_many :descriptions, class: "WikiEntry", as: :wikiable
  has_many :instructions, class: "WikiEntry", as: :wikiable
end


The option is class_name: http://guides.rubyonrails.org/association_basics.html#detailed-association-reference

Adbot
ADBOT LOVES YOU

Fillerbunny
Jul 25, 2002

so confused.

You're right, sorry. That was a typo in my example code.

But my original problem is still: how can I keep these properties separate in the database? How can I get a different record from SomeObject.first.descriptions.first than from SomeObject.first.instructions.first ?

EAT THE EGGS RICOLA
May 29, 2008

Fillerbunny posted:

You're right, sorry. That was a typo in my example code.

But my original problem is still: how can I keep these properties separate in the database? How can I get a different record from SomeObject.first.descriptions.first than from SomeObject.first.instructions.first ?

If you want to use a polymorphic association, you're going to just use an integer in the wikientry table to store the entry_type.

kayakyakr
Feb 16, 2004

Kayak is true
e: ^^ or an int value.

Fillerbunny posted:

You're right, sorry. That was a typo in my example code.

But my original problem is still: how can I keep these properties separate in the database? How can I get a different record from SomeObject.first.descriptions.first than from SomeObject.first.instructions.first ?

That seems like something more for scopes than for polymorphism. As you've got it now, the only things rails sees is is a wikiable, not which association it's attached to. Would it be so bad to create a "wiki_type" column (in addition to the wikiable_type column) in the WikiEntry class, then do:

Ruby code:
class SomeObject < ActiveRecord::Base
  has_many :wiki_entries, as: :wikiable do
    def descriptions
      where(:wiki_type => 'description')
    end
    def instructions
      where(:wiki_type => 'instruction')
    end
  end
end

kayakyakr fucked around with this message at 19:43 on Feb 24, 2014

Fillerbunny
Jul 25, 2002

so confused.

kayakyakr posted:

e: ^^ or an int value.


That seems like something more for scopes than for polymorphism. As you've got it now, the only things rails sees is is a wikiable, not which association it's attached to. Would it be so bad to create a "wiki_type" column (in addition to the wikiable_type column) in the WikiEntry class, then do:

Ruby code:
class SomeObject < ActiveRecord::Base
  has_many :wiki_entries, as: :wikiable do
    def descriptions
      where(:wiki_type => 'description')
    end
    def instructions
      where(:wiki_type => 'instruction')
    end
  end
end

Nope, that's not so bad at all. In fact, that's exactly what I was looking for. Normally I would go with an enumerated type, but I also like to be able to tell what type a thing is simply by looking at the records in the table, so I'll go with the string value.

Thanks for your help, guys. I haven't worked with scopes much/at all yet, so here's a good reason to read up on them.

kayakyakr
Feb 16, 2004

Kayak is true

Fillerbunny posted:

Nope, that's not so bad at all. In fact, that's exactly what I was looking for. Normally I would go with an enumerated type, but I also like to be able to tell what type a thing is simply by looking at the records in the table, so I'll go with the string value.

Thanks for your help, guys. I haven't worked with scopes much/at all yet, so here's a good reason to read up on them.

must admit, this is not exactly scopes, just taking advantage of arqi and the fact that you can define sub-methods on an association. I'm not even really sure what defining sub-methods is termed, but since traditional scopes have gone the way of the dodo, I'll call this scoping.



e: and this is why I dislike TDD. I spend as much time figuring out why the test suite is doing something as I do actually programming. In this case, I've got an embedded document that I'm not creating (yes yes, i'm using mongoid, so lame of me), and I'm not specifying in the factory, which is showing as nil in console and when i drop into debug, but exists when the test suite tests for its existence.

e2: ah, something that mongoid::matchers was doing to me. alright, expects and asserts syntax for any manual tests

kayakyakr fucked around with this message at 22:01 on Feb 24, 2014

Popper
Nov 15, 2006

The Milkman posted:

Because I didn't know about timeout :)

Yeah I wasn't crazy about that idea, that's why I asked. Never had to deal with time in this sort of way before, especially in a web application and figured there had to be something better than what I cooked up on a monday with little sleep. Thanks!



Edit: here's what I came up with this morning


initializer:
code:
Thread.new {
  loop do
    sleep 15.seconds # Just for testing
    image = SidebarImage.cycle_image
    puts "Cycling Sidebar Image: ##{image.position}: #{image.url}"
  end
}
in model:
code:
  def self.current
    @@current ||= first
  end

  def self.cycle_image
    if @@current == last
      @@current = first
    else
      @@current = find_by_position(@@current.position + 1)
    end
  end

This looks like the kind of code that if it breaks is terrible.
Why not just calculate the current image based on the time.

Something like
code:
  image_array[((Time.now.to_i - DateTime.now.midnight.to_i) / 15) % image_array.size]
Should return a different image every 15 seconds.

Chilled Milk
Jun 22, 2003

No one here is alone,
satellites in every home

Popper posted:

This looks like the kind of code that if it breaks is terrible.
Why not just calculate the current image based on the time.

Something like
code:
  image_array[((Time.now.to_i - DateTime.now.midnight.to_i) / 15) % image_array.size]
Should return a different image every 15 seconds.

Yeah, that was my original idea. What I ended up going with was this (based on Cocoa Crispies answer):
code:
  class << self
    def current
      @@current = published.offset(seconds_into_cycle / time_per_image).first
    end

    def seconds_into_cycle
      Time.now.to_i % cycle_time
    end

    def cycle_time
      @@cycle_time ||= Rails.application.config.sidebar_image_cycle_time
    end

    def time_per_image
      cycle_time / published.count
    end
  end

Phummus
Aug 4, 2006

If I get ten spare bucks, it's going for a 30-pack of Schlitz.
I'm cross-posting this from the general programming thread:

I am brand new to web development as a whole, and am trying to put together a simple application for patient checkin at work.

I crated a rails scaffold for providers. The model has 4 accessible fields:

Name
Email
Time1
Time2

On the providers/index page, I want to add a button at the end of each row that will populate time2 and keep me on the same page.

So I would have something like:

Name email Time1 Time2 Actions
Fred fred@aol.com 12:00 [Time2]
Joe joe@msn.com 1:00 [Time2]

When the user clicks on the Time2 button, it should populate time2 for that record and then reload/refresh/requery the page to display the new information.

My button on the form is
code:
<%= button_to "Time2", :action => "set_time2" %>
My problems are that I don't know where to define set_time2, and I don't know how to manage the routes so that the user stays on the same page.

Any help?

KoRMaK
Jul 31, 2012



Phummus posted:

I'm cross-posting this from the general programming thread:

I am brand new to web development as a whole, and am trying to put together a simple application for patient checkin at work.

I crated a rails scaffold for providers. The model has 4 accessible fields:

Name
Email
Time1
Time2

On the providers/index page, I want to add a button at the end of each row that will populate time2 and keep me on the same page.

So I would have something like:

Name email Time1 Time2 Actions
Fred fred@aol.com 12:00 [Time2]
Joe joe@msn.com 1:00 [Time2]

When the user clicks on the Time2 button, it should populate time2 for that record and then reload/refresh/requery the page to display the new information.

My button on the form is
code:
<%= button_to "Time2", :action => "set_time2" %>
My problems are that I don't know where to define set_time2, and I don't know how to manage the routes so that the user stays on the same page.

Any help?
:remote => true in your links and create js responses for them.

kayakyakr
Feb 16, 2004

Kayak is true

Phummus posted:

My problems are that I don't know where to define set_time2, and I don't know how to manage the routes so that the user stays on the same page.

Any help?

1) not sure what time1 and time2 represent, but you should use more descriptive column names and, depending on the purpose of the time1 and time2 fields, you may need to do a bit more in depth data modeling.

2) You can define your routes like:

Ruby code:
resources :providers do
  post :time, :on => :member
end
You would then add to participants controller

Ruby code:
def time
  # update the participant time
  redirect_to 'participants/index'
end
and finally, you could access it with

Ruby code:
<%= button_to 'Set Time 2', [:time, provider] %>
3) If you use remote => true, you can send a js or json response and never leave the page while button_to will refresh the page. You can also use something like:

Ruby code:
link_to 'Set Time 2', time_provider_path(provider), :method => :post
and get a link. Don't quote me on the path helper, you might run 'rake routes' to get the proper path helper for your new path.

Phummus
Aug 4, 2006

If I get ten spare bucks, it's going for a 30-pack of Schlitz.

kayakyakr posted:

1) not sure what time1 and time2 represent, but you should use more descriptive column names and, depending on the purpose of the time1 and time2 fields, you may need to do a bit more in depth data modeling.

This is just a test. My actual data model/database and application have useful names

kayakyakr posted:

2) You can define your routes like:

Ruby code:
resources :providers do
  post :time, :on => :member
end
I'm already at a loss as to what this is doing. If I read it correctly its saying on an HTTP Post call the 'time' method defined below?

kayakyakr posted:

You would then add to participants controller

Ruby code:
def time
  # update the participant time
  redirect_to 'participants/index'
end

This is the mehtod that does the redirect?

kayakyakr posted:


and finally, you could access it with

Ruby code:
<%= button_to 'Set Time 2', [:time, provider] %>
[.quote]

[quote="kayakyakr" post="426286712"]
3) If you use remote => true, you can send a js or json response and never leave the page while button_to will refresh the page. You can also use something like:

Ruby code:
link_to 'Set Time 2', time_provider_path(provider), :method => :post
and get a link. Don't quote me on the path helper, you might run 'rake routes' to get the proper path helper for your new path.

Again, not sure what is happening here either.

I've gone through Hartl's tutorial on Rails, and I feel like I'm still missing a big chunk of knowledge.

When I implemented these changes, and load providers/index, I get the error:
no block given (yield)

on the route:
code:
resources :providers do
  post :time, :on => member
end

Phummus fucked around with this message at 20:24 on Feb 27, 2014

kayakyakr
Feb 16, 2004

Kayak is true

Phummus posted:

I'm already at a loss as to what this is doing. If I read it correctly its saying on an HTTP Post call the 'time' method defined below?

You need to read this guide: http://guides.rubyonrails.org/routing.html, specifically section 2.10 Adding More RESTful Actions.

Phummus posted:

Again, not sure what is happening here either.

And this API doc: http://apidock.com/rails/ActionView/Helpers/UrlHelper/button_to

Phummus posted:

I've gone through Hartl's tutorial on Rails, and I feel like I'm still missing a big chunk of knowledge.

Yes, you are. Learn to rely on the official rails guides and API docs, they are very, very good.

"Phummus posted:

When I implemented these changes, and load providers/index, I get the error:
no block given (yield)

on the route:
code:
resources :providers do
  post :time, :on => member
end

Member is a symbol. ':member' and not just 'member'.

kayakyakr fucked around with this message at 20:34 on Feb 27, 2014

Phummus
Aug 4, 2006

If I get ten spare bucks, it's going for a 30-pack of Schlitz.
Well there's some progress. now that I've put the : in place rails starts and clicking on the botton doesn't throw an error. It does, however send me to /providers/5/time

5 being the index of the row I clicked on and time being the route defined in routes.rb?

When I go back to the index page, Time2 is not populated.

So it is still taking me off the page and isn't setting the time. I'll pick up those two links you mentioned to see if it lights any bulbs.

Molten Llama
Sep 20, 2006
Let's review what you've got. You've:
1. Created a controller method, time, to handle populating time2
2. Created a route which directs requests from the network to that method

If you haven't changed it, this is the body of that method:
code:
def time
  redirect_to 'participants/index'
end
What is this method doing?
What is this method not doing?

Phummus
Aug 4, 2006

If I get ten spare bucks, it's going for a 30-pack of Schlitz.

Molten Llama posted:


If you haven't changed it, this is the body of that method:
code:
def time
  redirect_to 'participants/index'
end
What is this method doing?
What is this method not doing?

I didn't create any new controllers, the only controller I have is for providers.

The method is for providers, so my method uses providers instead of participants.

It redirects me to a new page. I assumed it would be redirecting me to the participants/index page, however, when I invoke it through the button click, it redirects me to providers/{someindex}/time.

It does not update any of the database fields.

kayakyakr
Feb 16, 2004

Kayak is true

Phummus posted:

I didn't create any new controllers, the only controller I have is for providers.

The method is for providers, so my method uses providers instead of participants.

It redirects me to a new page. I assumed it would be redirecting me to the participants/index page, however, when I invoke it through the button click, it redirects me to providers/{someindex}/time.

It does not update any of the database fields.

It does not update any of the database fields because you haven't programmed any updates in. Rails does a lot of things for you, but it isn't magic.

The redirect_to should be redirecting to the index page. try:

Ruby code:
def time
  # update provider here
  redirect_to providers_path
end

Peristalsis
Apr 5, 2004
Move along.
I have a set of models that all need the same validation code (just checking a common field value against a controlled vocabulary). I'd prefer not to repeat this code in every one of the models. I created a mixin module for the vocabulary itself, but I don't think the validations can be in a mixin, can they? Is my best bet to put a new superclass with that validation between ActiveRecord and my models? Or should I not be sweating a single line of repeated validation code?

kayakyakr
Feb 16, 2004

Kayak is true

Peristalsis posted:

I have a set of models that all need the same validation code (just checking a common field value against a controlled vocabulary). I'd prefer not to repeat this code in every one of the models. I created a mixin module for the vocabulary itself, but I don't think the validations can be in a mixin, can they? Is my best bet to put a new superclass with that validation between ActiveRecord and my models? Or should I not be sweating a single line of repeated validation code?

Read through: http://api.rubyonrails.org/classes/ActiveSupport/Concern.html

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

edit: never mind, I'm retarded

I need Pardot or someone else who is good at postgres to help me inserting a string with quotation characters

Ruby code:
    def get_channel_notification_sql(user_ids, channel_id, message)
      support_user_id = user_manager.find_user_by_email("support@my-company.com").try(:id)

      user_notifications_sql = user_ids.map do |id|
        message = UserNotificationRecord.connection.quote_string(message)
        "(#{id}, '#{message}', 'channel', '/channels/#{channel_id}', NOW(), NOW(), #{support_user_id})"
      end

      return "INSERT INTO table (user_id, message, notification_type, notification_url, created_at, updated_at, referenced_user_id) VALUES #{user_notifications_sql.join(", ")}"
    end

# ...
 
    message = "These pretzels... they're makin' me thirsty!"
    user_notification_manager.create_channel_user_notifications(channel.id, message)

If I comment out the `message =...` line I get an error:
code:
ActiveRecord::StatementInvalid: PG::Error: ERROR:  syntax error at or near "re"
LINE 1: ...enced_user_id) VALUES (1, 'These pretzels... they're makin' ...
If I don't, I get this fun thing:
code:
expected: "These pretzels... they're makin' me thirsty!"
     got: "These pretzels... they''''''''''''''''''''''''''''''''re makin'''''''''''''''''''''''''''''''' me thirsty!" (using ==)

A MIRACLE fucked around with this message at 17:16 on Mar 10, 2014

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

A MIRACLE posted:

I'm retarded

Ruby code:
    def get_channel_notification_sql(user_ids, channel_id, message)
      support_user_id = user_manager.find_user_by_email("support@my-company.com").try(:id)

      user_notifications_sql = user_ids.map do |id|
        message = UserNotificationRecord.connection.quote_string(message)
        "(#{id}, '#{message}', 'channel', '/channels/#{channel_id}', NOW(), NOW(), #{support_user_id})"
      end

      return "INSERT INTO table (user_id, message, notification_type, notification_url, created_at, updated_at, referenced_user_id) VALUES #{user_notifications_sql.join(", ")}"
    end
Use bound parameters, and if you use ActiveRecord and not just SQL you don't have to worry about any of that poo poo.

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

Does activerecord have a way to do a mass row insert?

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.

A MIRACLE posted:


Does activerecord have a way to do a mass row insert?

No. Anyhow, I know that activerecord-import does approximately what you want to do, but I haven't personally used it. Caveat emptor.

EAT THE EGGS RICOLA
May 29, 2008

Doing it as a single mass insert is the fastest way that I know of to do it.

code:
Testing various insert methods for 10000 inserts
ActiveRecord without transaction:
 14.930000   0.640000  15.570000 ( 18.898352)
ActiveRecord with transaction:
 13.420000   0.310000  13.730000 ( 14.619136)
  1.29x faster than base
Raw SQL without transaction:
  0.920000   0.170000   1.090000 (  3.731032)
  5.07x faster than base
Raw SQL with transaction:
  0.870000   0.150000   1.020000 (  1.648834)
  11.46x faster than base
Single mass insert:
  0.000000   0.000000   0.000000 (  0.268634)
  70.35x faster than base
ActiveRecord::Extensions mass insert:
  6.580000   0.280000   6.860000 (  9.409169)
  2.01x faster than base
ActiveRecord::Extensions mass insert without validations:
  6.550000   0.240000   6.790000 (  9.446273)
  2.00x faster than base

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

Smol posted:

No. Anyhow, I know that activerecord-import does approximately what you want to do, but I haven't personally used it. Caveat emptor.

I looked at this but decided to just raw-dog it since we're only going to use it in one place. And I didn't really want to loop through 70,000 users or so in vanilla activerecord

kayakyakr
Feb 16, 2004

Kayak is true

A MIRACLE posted:

Does activerecord have a way to do a mass row insert?

You're doing it right. I assume that you figured out what your issue is and I don't need to point out that you're calling quote_string for each user_id. By the end of that loop, you've quoted the string 5 times for a total of 32 apostrophes. Powers of 2 are a bitch.

And depending how your test case is written, what that should read as is "These pretzels... they''re makin'' me thirsty!" Escaping ' in postgres is written as ''.

e: also you should do it in batches. test out your use case between 100, 500, 1000, etc batch sizes, you should find a sweet spot.

kayakyakr fucked around with this message at 20:38 on Mar 10, 2014

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.

A MIRACLE posted:

I looked at this but decided to just raw-dog it since we're only going to use it in one place. And I didn't really want to loop through 70,000 users or so in vanilla activerecord

Good choice.

Pardot
Jul 25, 2001




$$ strings are neat:

code:
=# select $$this "is ' good '" and stuff $ yes$$;
              ?column?
------------------------------------
 this "is ' good '" and stuff $ yes

=# select $foo$but I need $$ too for some reason$foo$;
             ?column?
-----------------------------------
 but I need $$ too for some reason
For the app I mantain that happens-to-be-rails-but-i-wish-it-wasnt I got angry at ActiveRecord and arel because I couldn't figure out how to use arel but not be tied to a model, so I ended up doing this:

code:
    QUERY = %q(
      select
        fields
      from
        tables
      where
         preciates
         and u.id = $1
     ;
    )

    def self.raw_json(user_id)
      result = ActiveRecord::Base.connection.raw_connection.exec(QUERY , [user_id])
      Yajl::Encoder.encode result.to_a
    end
which is using the raw PGConn class to run the query with proper parameter binding.

Legacyspy
Oct 25, 2008
So I am trying to debug a massive slow down in an application.

code:
Completed in 588959ms (View: 0, DB: 556627) | 200 OK [/update_status?id=1,2,3,4,5,6...,200&value=1]
Ten minutes! So what happens is you select ~ 200 items, then click a button, and this update_status method is called and the 200 items are passed to that. It takes 10 minutes.

I have a test for this that does EXACTLY the same method on exactly the same parameters, on exactly the same data. It takes 60 seconds.

Any ideas?

kayakyakr
Feb 16, 2004

Kayak is true

Legacyspy posted:

So I am trying to debug a massive slow down in an application.

code:
Completed in 588959ms (View: 0, DB: 556627) | 200 OK [/update_status?id=1,2,3,4,5,6...,200&value=1]
Ten minutes! So what happens is you select ~ 200 items, then click a button, and this update_status method is called and the 200 items are passed to that. It takes 10 minutes.

I have a test for this that does EXACTLY the same method on exactly the same parameters, on exactly the same data. It takes 60 seconds.

Any ideas?

60 seconds is still too long to churn. How big is your production database? Does your test DB have just those 200 items while your production have more? Do you have indexes set for those tables?

Things you should consider when dealing with that much data: update with raw SQL instead of churning through active record. Update in batches. Select and update in the same step instead of selecting each of 200 items and then updating each of 200 items.

If you can't get it to < 2 seconds if you're doing AJAX or < 1 second if you're doing classic form post, then you need to push that off into a background task (I recommend sucker punch as it runs threaded inside your server).

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Legacyspy posted:

So I am trying to debug a massive slow down in an application.

code:
Completed in 588959ms (View: 0, DB: 556627) | 200 OK [/update_status?id=1,2,3,4,5,6...,200&value=1]
Ten minutes! So what happens is you select ~ 200 items, then click a button, and this update_status method is called and the 200 items are passed to that. It takes 10 minutes.

I have a test for this that does EXACTLY the same method on exactly the same parameters, on exactly the same data. It takes 60 seconds.

Any ideas?

What does New Relic say it's spending its time on? If it's slow in development, you can use developer mode.

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.

Legacyspy posted:

So I am trying to debug a massive slow down in an application.

code:
Completed in 588959ms (View: 0, DB: 556627) | 200 OK [/update_status?id=1,2,3,4,5,6...,200&value=1]
Ten minutes! So what happens is you select ~ 200 items, then click a button, and this update_status method is called and the 200 items are passed to that. It takes 10 minutes.

I have a test for this that does EXACTLY the same method on exactly the same parameters, on exactly the same data. It takes 60 seconds.

Any ideas?

Show us the query (or queries), your schema, how many rows there are in the respective tables and which database you are using. If possible, output from PostgreSQL's EXPLAIN ANALYZE or MySQL's EXPLAIN will help as well.

Newbsylberry
Dec 29, 2007

I Swim in drag shorts because I have a SMALL PENIS
I am going through: http://alexpotrykus.com/blog/2013/12/07/angularjs-with-rails-4-part-1/ this tutorial to set up Angular with rails4.02. I am getting stuck with "ActionController::UnknownFormat" after I set up the api to deliver JSON in routes and the controller. I can access the JSON at /api/risks but when I try and access the root after setting up my RiskCtrl it gives me the UnknownFormat error.

EDIT - I figured out the issue I was having, I had my risks index as my root, instead of having a different page being my root and calling on my Risks API. Sucks to suck I guess

Newbsylberry fucked around with this message at 18:24 on Mar 13, 2014

Newbsylberry
Dec 29, 2007

I Swim in drag shorts because I have a SMALL PENIS
Terribly sorry for the double post, but has anyone had any success and would be kind enough to explain using has_many, belongs_to, etc. with angular as your front end?

I have found a couple of resources online, and I am guessing I need to do it through my services, but it isn't really clicking for me. If anybody has been through this themselves and can help me figure it out, I would throw an upgrade their way.

xtal
Jan 9, 2011

by Fluffdaddy
Coming back to Rails development and I see that unicorn is included in the default Gemfile now. Is that the preferred web server or do people still use Thin / Passenger?

Vulture Culture
Jul 14, 2003

I was never enjoying it. I only eat it for the nutrients.

xtal posted:

Coming back to Rails development and I see that unicorn is included in the default Gemfile now. Is that the preferred web server or do people still use Thin / Passenger?
Unicorn is the fastest option for most applications, but it's complex and it needs a good amount of hand-holding to get the performance options right. Thin is still a good option if you want something that will work reasonably well for most apps out of the box. There's lots of newer servers like Puma, adding more confusion.

kayakyakr
Feb 16, 2004

Kayak is true

xtal posted:

Coming back to Rails development and I see that unicorn is included in the default Gemfile now. Is that the preferred web server or do people still use Thin / Passenger?

Thin seems to be falling out of favor because Puma does the same thing for MRI without having to rely on EventMachine and does more when you hook it up to jruby or rubinius. Unicorn is still my standard, but if you want websocket support, you should also use a server like Puma.

yoyodyne
May 7, 2007
Suppose that a user is signed into a rails app (with the devise gem) with an ember front end. I want to be able to log the user out after a certain amount of time (probably a little longer than the length of a regular workday) regardless of activity (this is key), and have the user come in the next morning with the login screen on their browser. I've had some success using a modification of the method here (https://www.coffeepowered.net/2013/09/26/rails-session-cookies/), modified such that I don't refresh the ttl. This partially works, but (1) it doesn't automatically redirect to the login screen, and (2) because of the way some of the ember stuff is set up, only upon clicking certain links does it redirect to the login page.

I was thinking of making a worker that checks every minute or so to see if a user has been logged in for > x.hours, but I was discouraged, since it would likely use too many resources.

Is there another approach that would work well for this that I haven't thought of yet?

kayakyakr
Feb 16, 2004

Kayak is true

yoyodyne posted:

Suppose that a user is signed into a rails app (with the devise gem) with an ember front end. I want to be able to log the user out after a certain amount of time (probably a little longer than the length of a regular workday) regardless of activity (this is key), and have the user come in the next morning with the login screen on their browser. I've had some success using a modification of the method here (https://www.coffeepowered.net/2013/09/26/rails-session-cookies/), modified such that I don't refresh the ttl. This partially works, but (1) it doesn't automatically redirect to the login screen, and (2) because of the way some of the ember stuff is set up, only upon clicking certain links does it redirect to the login page.

I was thinking of making a worker that checks every minute or so to see if a user has been logged in for > x.hours, but I was discouraged, since it would likely use too many resources.

Is there another approach that would work well for this that I haven't thought of yet?

Devise includes a "remember_for" option that you can set on the model. ex:

Ruby code:
class User
  devise :rememberable, remember_for: 10.hours
end
see the devise readme and: http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Rememberable

Adbot
ADBOT LOVES YOU

enki42
Jun 11, 2001
#ATMLIVESMATTER

Put this Nazi-lover on ignore immediately!

yoyodyne posted:

This partially works, but (1) it doesn't automatically redirect to the login screen, and (2) because of the way some of the ember stuff is set up, only upon clicking certain links does it redirect to the login page.

I could be wrong, but it sounds like you're all set from the cookie side, and you just need to detect whether the user is logged in or not from the javascript side, and redirect to the login page once their session has expired.

I think you'd probably need some sort of "heartbeat" type call on a controller that could tell you whether you have an active session, and ping it every minute or so to see if your user is still active. If you don't get a "logged-in" status from that service, redirect to the login page.

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