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
KoRMaK
Jul 31, 2012



Is there no builtin way to convert a TimeWithZone to a DateTime? Currently it looks like I have to do DateTime.new(mytime.year, mytime.day, mytime.month)

Adbot
ADBOT LOVES YOU

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.

http://stackoverflow.com/questions/4494954/convert-activesupporttimewithzone-to-datetime

KoRMaK
Jul 31, 2012



I am so embarrassed, I missed #to_date

kayakyakr
Feb 16, 2004

Kayak is true

Pollyanna posted:

So if I use Ember with Rails, I end up having at least two Models, two Controllers, and three Views? That...isn't very dry. Not to say that code benchmarking is the point of coding, but whether something makes sense or not affects whether I know what the gently caress I'm doing or not.

You misunderstand.

You wind up with a model on the rails side and some representation on the JS side (this could just be retrieval as a 'route' or a model proxy object).

You have a controller on the rails side handling persistence and protected business logic and a controller on the JS side handing all of the JS actions.

You have a template on the JS side and may have a 'view' if you need to do anything particularly special that requires JS, and you may use something like jbuilder to do a view on the rails side or you could just use .as_json.

So yes, you can have 2 models, 2 controllers, and 3 views, but they each perform very different tasks for your codebase.

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.

kayakyakr posted:

You misunderstand.

You wind up with a model on the rails side and some representation on the JS side (this could just be retrieval as a 'route' or a model proxy object).

You have a controller on the rails side handling persistence and protected business logic and a controller on the JS side handing all of the JS actions.

You have a template on the JS side and may have a 'view' if you need to do anything particularly special that requires JS, and you may use something like jbuilder to do a view on the rails side or you could just use .as_json.

So yes, you can have 2 models, 2 controllers, and 3 views, but they each perform very different tasks for your codebase.

Just going to chime in that the API/JS solution will require more lines of code, but just the separation of persistence/business/ui/whatever logic it naturally gives makes it worth it in my opinion for any nontrivial application. For some internal CRUD app you're going to whip up in 3 days, it's not worth it.

Pollyanna
Mar 5, 2005

Milk's on them.


That, or you don't know how to do anything else, like me.

kayakyakr
Feb 16, 2004

Kayak is true

Pollyanna posted:

That, or you don't know how to do anything else, like me.

So... learn something new?

JS frameworks are useful for when you want to build very interactive, non-trivial interfaces. I used ExtJs for a while, but much prefer Ember/Angular/Backbone. Also write old fashioned CRUD apps, combo apps (which backbone is good for), turbolinks apps. It's all on what you're doing. If your app is front-end, user interaction heavy, then a JS framework is a good choice.

xtal
Jan 9, 2011

by Fluffdaddy
Rails is great for JavaScript apps actually if you think of it as Sinatra with an asset pipeline. Your Rails app will only handle compiling your JavaScript and reading or writing to the database via a RESTful API. Your JavaScript will do the routing and the rendering. It's not practically correct to say that one or the other does the modeling: they both do the modeling, but JavaScript reads from your API and your API reads from your database. They're both different representations of the same model.

You also don't necessarily need to write JavaScript, but I get what you're saying. You could make a full web app in Opal or ClojureScript or whatever that simply interfaces with your Rails API. Consider also that it's very easy to build a new phone app or desktop app or command line tool or whatever when your API is your first-class citizen.

xtal fucked around with this message at 01:06 on Jul 11, 2014

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.

Rails is really great for javascript apps. as_json is a godsend

Pollyanna
Mar 5, 2005

Milk's on them.


Has anyone used foundation-rails to include Foundation in their apps? Cause I just installed it, but it's giving me an Uncaught TypeError: undefined is not a function message on this line in application.js:

JavaScript code:
$(function() { $(document).foundation(); });
The only reason I can think of for this happening is the Foundation JS not being included in the asset pipeline somehow. Also, none of the CSS loads, either. Any ideas?

kayakyakr
Feb 16, 2004

Kayak is true

Pollyanna posted:

Has anyone used foundation-rails to include Foundation in their apps? Cause I just installed it, but it's giving me an Uncaught TypeError: undefined is not a function message on this line in application.js:

JavaScript code:
$(function() { $(document).foundation(); });
The only reason I can think of for this happening is the Foundation JS not being included in the asset pipeline somehow. Also, none of the CSS loads, either. Any ideas?

I'm using it in one of my projects. You need your application.js to look like:

JavaScript code:
//= require jquery
//= require foundation
//= require_tree .

$(function() { $(document).foundation(); });
if that's what it looks like, then I'd look to see what your browser is loading.

A MIRACLE posted:

Rails is really great for javascript apps. as_json is a godsend

I use jbuilder because I want more control over what is sent across the wire

Molten Llama
Sep 20, 2006

Pollyanna posted:

The only reason I can think of for this happening is the Foundation JS not being included in the asset pipeline somehow. Also, none of the CSS loads, either. Any ideas?

If you didn't use their generator (rails g foundation:install), you need to manually add it to your application.js and application.css (and parts of it to the asset pipeline) as detailed in the docs.

Adding it to the Gemfile only makes it available to use.

Molten Llama fucked around with this message at 20:55 on Jul 11, 2014

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.

kayakyakr posted:

I use jbuilder because I want more control over what is sent across the wire

Cool, I'll check it out. as_json has overrides that I use though, I never just call it vanilla

Slow News Day
Jul 4, 2007

kayakyakr posted:

So... learn something new?

JS frameworks are useful for when you want to build very interactive, non-trivial interfaces. I used ExtJs for a while, but much prefer Ember/Angular/Backbone. Also write old fashioned CRUD apps, combo apps (which backbone is good for), turbolinks apps. It's all on what you're doing. If your app is front-end, user interaction heavy, then a JS framework is a good choice.

Can you qualify this a little? I'm still a beginner (~6 months) and I don't know what qualifies as "very interactive" or "non-trivial."

I have a training app that's used internally in my company, and while a lot of the usage involves reading and completing courses, it does have some interactive elements. For example, admin users can build lists of courses via drag and drop, and the courses on the lists as well as their positions need to be recorded in the database. They can also increase and decrease the count of certain items via plus and minus buttons, and the app needs to update the current count in real-time. Right now I'm handling those kinds of interactions via AJAX calls and short snippets of jQuery that are sent back to the client. It hasn't gotten overwhelming yet, but I also notice that it's not very DRY.

At what point would I start needing a front-end framework? Are there rules of thumb to follow, or is it something I "get" once I actually get some experience with one?

kayakyakr
Feb 16, 2004

Kayak is true

enraged_camel posted:

Can you qualify this a little? I'm still a beginner (~6 months) and I don't know what qualifies as "very interactive" or "non-trivial."

I have a training app that's used internally in my company, and while a lot of the usage involves reading and completing courses, it does have some interactive elements. For example, admin users can build lists of courses via drag and drop, and the courses on the lists as well as their positions need to be recorded in the database. They can also increase and decrease the count of certain items via plus and minus buttons, and the app needs to update the current count in real-time. Right now I'm handling those kinds of interactions via AJAX calls and short snippets of jQuery that are sent back to the client. It hasn't gotten overwhelming yet, but I also notice that it's not very DRY.

At what point would I start needing a front-end framework? Are there rules of thumb to follow, or is it something I "get" once I actually get some experience with one?

Sadly, it's not easy to qualify. It depends on your goals: is every page going to have some sort of JS-only interaction? Are you building out huge lists and tables that you need to be able to change on the fly? If so, then you probably need a JS framework.

Internal projects (and even some external projects) I usually attack on a sliding scale. I'll start rails-only, add in some functionality, and then when I have to start doing things that are too complex for 20-30 lines of jquery stuff, I'll integrate first my own little framework, then look at pulling in a larger framework.

It helps that my typical JS code is structured pretty similarly to how a framework would be structured.

JavaScript code:
// for turbolinks (JS code is persisted)
(function(){
  var self, controller = function(){
    $(document).on('click', '.item', this.doSomething);
  };

  controller.prototype = {
    doSomething: function(){
    },
    doSomethingElse: function(){
    }
  };

  window.ControllerSingleton = self = new controller();
})();
That translates into Angular or Backbone code fairly easily. Ember is different. A lot more structure.

I will admit, the project I've been working on this week is functional rather than prototypal. I don't like it, but it is what it is.

Pollyanna
Mar 5, 2005

Milk's on them.


I'm not sure why, but I started a new app and Foundation works perfectly well this time. I think the instructions on the Foundation site are a little inaccurate/out-of-date. v:shobon:v

I have been trying to learn more about how JS does MVC (what the gently caress Ember), but that's for another thread.

xenilk
Apr 17, 2004

ERRYDAY I BE SPLIT-TONING! Honestly, its the only skill I got other than shooting the back of women and calling it "Editorial".
I have a bit of a brainfart right now and hope you guys can help me out!

I have an application that has unit controller + a lease controller (a lease belongs to a unit; a unit has many leases)

In the lease model I created the following method

code:
def ending_soon?
  	@now = Date.today()
  	if(self.date_end >= @now && @now >= self.date_start)
  		(@now + 1.month) >= self.date_end
  	else
  		false
  	end
end
That all works fine and when I list the leases I can know if they are ending soon...

That being said, when I list each unit I would love to know if they have a lease that is ending soon and can't wrap my head around it... do I have to create a "has_lease_ending_soon?" method on the door level or is there a more functional way to do it?

kayakyakr
Feb 16, 2004

Kayak is true

xenilk posted:

I have a bit of a brainfart right now and hope you guys can help me out!

I have an application that has unit controller + a lease controller (a lease belongs to a unit; a unit has many leases)

In the lease model I created the following method

code:
def ending_soon?
  	@now = Date.today()
  	if(self.date_end >= @now && @now >= self.date_start)
  		(@now + 1.month) >= self.date_end
  	else
  		false
  	end
end
That all works fine and when I list the leases I can know if they are ending soon...

That being said, when I list each unit I would love to know if they have a lease that is ending soon and can't wrap my head around it... do I have to create a "has_lease_ending_soon?" method on the door level or is there a more functional way to do it?

Ruby code:
Unit.joins(:leases).where("leases.date_end > (now() - interval '1 day') AND leases.date_end < (now() + interval '1 month')")
If you're using postgres. Similar if you're using mysql, but without some of the postgres shortcuts.

You can shorten your method like so:

Ruby code:
def ending_soon?
  self.date_end >= Date.today && self.date_end < 1.month.from_now
end

xenilk
Apr 17, 2004

ERRYDAY I BE SPLIT-TONING! Honestly, its the only skill I got other than shooting the back of women and calling it "Editorial".

kayakyakr posted:

Ruby code:
Unit.joins(:leases).where("leases.date_end > (now() - interval '1 day') AND leases.date_end < (now() + interval '1 month')")
If you're using postgres. Similar if you're using mysql, but without some of the postgres shortcuts.

You can shorten your method like so:

Ruby code:
def ending_soon?
  self.date_end >= Date.today && self.date_end < 1.month.from_now
end

Thank you!

ended up shortening ending_soon? to
Ruby code:
  def ending_soon?
    self.date_end >= Date.today && self.date_end <= 1.month.from_now.to_date
  end
since without the .to_date I was getting this error:
comparison of Date with ActiveSupport::TimeWithZone failed

Also, thanks for the example, exactly what I wanted! :)

Thalagyrt
Aug 10, 2006

xenilk posted:

Thank you!

ended up shortening ending_soon? to
Ruby code:
  def ending_soon?
    self.date_end >= Date.today && self.date_end <= 1.month.from_now.to_date
  end
since without the .to_date I was getting this error:
comparison of Date with ActiveSupport::TimeWithZone failed

Also, thanks for the example, exactly what I wanted! :)

Sounds like there's some confusion in your code somewhere based on that error - part of it is using naive datetimes, the other is using time-zone aware datetimes. You should really look further into what's happening instead of bandaging it as you might end up with dates being stored/retrieved incorrectly or other time-zone related problems if you're not using time-zone aware datetimes across the board. Date.today for example is one that you shouldn't use - use Time.zone.today instead to get a time-zone aware date object.

kayakyakr
Feb 16, 2004

Kayak is true

Thalagyrt posted:

Sounds like there's some confusion in your code somewhere based on that error - part of it is using naive datetimes, the other is using time-zone aware datetimes. You should really look further into what's happening instead of bandaging it as you might end up with dates being stored/retrieved incorrectly or other time-zone related problems if you're not using time-zone aware datetimes across the board. Date.today for example is one that you shouldn't use - use Time.zone.today instead to get a time-zone aware date object.

He's storing it as a Date type in the database. Depending on the intent, he could be ok with just using date. Probably would be better to store as a time with zone, though.

Thalagyrt
Aug 10, 2006

kayakyakr posted:

He's storing it as a Date type in the database. Depending on the intent, he could be ok with just using date. Probably would be better to store as a time with zone, though.

Hm, yeah that does just return a Date. Still worth storing it timezone aware in my opinion. The thing about a naive date is that the point where it rolls over from one day to the next is going to vary based on the timezone settings on the server, which may be undesirable.

Pardot
Jul 25, 2001




Always store dates (at least in postgres) timestamp with timezone aka timestamptz. It is never correct to use simply timestamp.

Rails defaults to the wrong thing. If you rely on rails timestamp migrations your database is wrong.

xenilk
Apr 17, 2004

ERRYDAY I BE SPLIT-TONING! Honestly, its the only skill I got other than shooting the back of women and calling it "Editorial".
I'm a bit confused, how do I store the the date with the timezone? Do I have to change my Date field to Datetime and simply have my date like 2014-07-18 00:00:00 ?

Edit: Intent is to store the beginning and end of a lease... I believe I don't need much more information than the date since when you lease an apartment for example you don't really put the time of when the lease starts/ends.

xenilk fucked around with this message at 14:38 on Jul 18, 2014

kayakyakr
Feb 16, 2004

Kayak is true

xenilk posted:

I'm a bit confused, how do I store the the date with the timezone? Do I have to change my Date field to Datetime and simply have my date like 2014-07-18 00:00:00 ?

Edit: Intent is to store the beginning and end of a lease... I believe I don't need much more information than the date since when you lease an apartment for example you don't really put the time of when the lease starts/ends.

The problem is that you want to store the start or end of the day in the certain time zone that the unit is in. Otherwise, if your server is in New York and your unit is in Hawaii, it very well may show the lease ending a day early, depending on what time you check the status.

This is a problem where you either have to deal with the pain of time zones on the save or on the query. To deal on the save, you have to make sure you're sending back the user's time zone so that you save the date with the proper zone. There are ways to infer this from the request IP, but I wouldn't recommend any of those ways.

On the flip side, you can store it as a date and when the user queries, send that user's current date back. This is adequate, but not ideal since if a manager travels or simply lives in a different time zone, their dates could potentially be off.

Third option is to infer the time zone based on the location of the unit. This would be best done on the storage side because it's hard to determine that data in the query.


e: fourth option is to ignore the issue completely which is a good option if the software is for local use only and will not cross time zones.

xtal
Jan 9, 2011

by Fluffdaddy
If you're storing a date in your database and using a time zone that isn't UTC, that's the real problem.

Pardot
Jul 25, 2001




xtal posted:

If you're storing a date in your database and using a time zone that isn't UTC, that's the real problem.

timestamptz normalizes and only actually stores it as utc. It takes care of everything.

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.

Time zones can be pretty easy to gently caress up if you're not paying attention, which usually I am not
code:
irb(main):041:0> Time.now.in_time_zone("Eastern Time (US & Canada)").sunday.end_of_day
=> Sun, 20 Jul 2014 23:59:59 EDT -04:00
irb(main):042:0> Time.now.sunday.end_of_day.in_time_zone("Eastern Time (US & Canada)")
=> Sun, 20 Jul 2014 19:59:59 EDT -04:00

xenilk
Apr 17, 2004

ERRYDAY I BE SPLIT-TONING! Honestly, its the only skill I got other than shooting the back of women and calling it "Editorial".

kayakyakr posted:

The problem is that you want to store the start or end of the day in the certain time zone that the unit is in. Otherwise, if your server is in New York and your unit is in Hawaii, it very well may show the lease ending a day early, depending on what time you check the status.

This is a problem where you either have to deal with the pain of time zones on the save or on the query. To deal on the save, you have to make sure you're sending back the user's time zone so that you save the date with the proper zone. There are ways to infer this from the request IP, but I wouldn't recommend any of those ways.

On the flip side, you can store it as a date and when the user queries, send that user's current date back. This is adequate, but not ideal since if a manager travels or simply lives in a different time zone, their dates could potentially be off.

Third option is to infer the time zone based on the location of the unit. This would be best done on the storage side because it's hard to determine that data in the query.


e: fourth option is to ignore the issue completely which is a good option if the software is for local use only and will not cross time zones.

Thanks for this, it helped me grasping the whole problem. For now it's for a small project that will be used locally but I can see how this could be problematic for many different reasons.

I will need to learn more about how I can address this.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

Pardot posted:

timestamptz normalizes and only actually stores it as utc. It takes care of everything.

If timestamp and timestamptz both store the value in utc then how is Rails wrong? Isn't Rails handling timezones itself, independent from any database?

kayakyakr
Feb 16, 2004

Kayak is true

Nolgthorn posted:

If timestamp and timestamptz both store the value in utc then how is Rails wrong? Isn't Rails handling timezones itself, independent from any database?

Rails Time.now works in the current timezone, not in UTC. Timestamptz understands Rails's timezone and can handle it.

KoRMaK
Jul 31, 2012



I started using byebug for debugging. If your using Rails 3.2, it's the only one that works apparently. debugger gem crashes and the other popular one didn't either.

kayakyakr
Feb 16, 2004

Kayak is true

KoRMaK posted:

I started using byebug for debugging. If your using Rails 3.2, it's the only one that works apparently. debugger gem crashes and the other popular one didn't either.

But go back to debugger in rails 4 because byebug has issues.

Sub Par
Jul 18, 2001


Dinosaur Gum
I have some outbound links on my rails app (Rails 4, running on Heroku). When they are clicked, they are tracked in my database. One of the fields I'm hoping to capture about each click event is the IP address of the person clicking. I am having a devil of a time doing this. I'm currently doing this here thing:
code:
@click.request_ip = request.env["X_FORWARDED_FOR"]
Which works some times but not others, and I can't figure out why. The consensus on stackoverflow seems to be "doing this is hard when you're hosted on Heroku and oh by the by people can spoof IPs", but I don't care about spoofing and Heroku's docs seem to indicate that I'm doing it right. Am I?

xenilk
Apr 17, 2004

ERRYDAY I BE SPLIT-TONING! Honestly, its the only skill I got other than shooting the back of women and calling it "Editorial".
Any of you have experience with the CarrierWave gem?

I'm thinking of installing that and fog and creating a polymorphic table called media that could be references on other parts of the application. Does that sound about right? I'm a bit confused with the documentation but I'd be happy to hear some of you comment on that.

Jaded Burnout
Jul 10, 2004


kayakyakr posted:

But go back to debugger in rails 4 because byebug has issues.

debugger don't work so well with Ruby 2.

Jaded Burnout
Jul 10, 2004


Sub Par posted:

I have some outbound links on my rails app (Rails 4, running on Heroku). When they are clicked, they are tracked in my database. One of the fields I'm hoping to capture about each click event is the IP address of the person clicking. I am having a devil of a time doing this. I'm currently doing this here thing:
code:
@click.request_ip = request.env["X_FORWARDED_FOR"]
Which works some times but not others, and I can't figure out why. The consensus on stackoverflow seems to be "doing this is hard when you're hosted on Heroku and oh by the by people can spoof IPs", but I don't care about spoofing and Heroku's docs seem to indicate that I'm doing it right. Am I?

I believe X_FORWARDED_FOR is only populated if the request is through a proxy. There's a method in Rack (or maybe Rails) which will defer down the stack until it finds an IP, suggest you use that one.

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.
X-forwarded-for is added by reverse proxies (e.g. nginx in front of your rails app). If you're not seeing it in development, then that's probably the reason. Anyhow, ActionContoller::Request#remote_ip is what you're looking for.

kayakyakr
Feb 16, 2004

Kayak is true

Arachnamus posted:

debugger don't work so well with Ruby 2.

ruby-debug and debugger are built in to ruby 2, no? debugger statement works as if you had the debugger gem installed.

Adbot
ADBOT LOVES YOU

Sub Par
Jul 18, 2001


Dinosaur Gum

Smol posted:

X-forwarded-for is added by reverse proxies (e.g. nginx in front of your rails app). If you're not seeing it in development, then that's probably the reason. Anyhow, ActionContoller::Request#remote_ip is what you're looking for.

This is what I originally had, but because of the way Heroku works, I was getting nothing but 10.xx.xx.xx IPs that were likely some kind of Heroku load-balancing or whatever. Anyway I'm now trying this:
code:
@click.request_ip = request.env['HTTP_X_REAL_IP'] ||= request.env['REMOTE_ADDR']
We'll see how that goes.

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