Re: [Rails-core] Proposal: make it clearer which persistence methods do callbacks/validations

2018-09-02 Thread Matt Jones


> On Aug 27, 2018, at 8:43 PM, Dana Sherson  wrote:
> 
> Currently many of the persistence methods all have different behaviours when 
> it comes to whether setters are called, and validations and or callbacks are 
> run,
> Knowing what happens requires deeper knowledge of rails than just reading the 
> method name
> 
> This can be confusing for newcomers and even people very familiar with rails 
> will need to double check which does what.

IMO most of these are clarified by clicking the “source” link under the method 
in the docs to see how they use the core primitives - i.e., `update` calls 
`save` internally.

> save(validate: false) => callbacks: yes, validations: no, 
> only_save_mentioned_columns: N/A
> save => callbacks: yes, validations: yes, touch: yes, 
> only_save_mentioned_columns: N/A
> save(touch: false) => callbacks: yes, validations: yes, touch: no, 
> only_save_mentioned_columns: N/A
> save(validate: false, touch: false) => callbacks: yes, validations: no, 
> touch: no, only_save_mentioned_columns: N/A

I doubt this is anybody’s favorite interface, but it’s better than the old 
`save(false)`. AFAIK it’s partly an artifact of how `save` is implemented as a 
stack of included modules.

> update/update_attributes => callbacks: yes, validations: yes, setters: yes, 
> touch: yes, only_save_mentioned_columns: no
> update_attribute => callbacks: yes, validations: no, setters: yes, touch: 
> yes, only_save_mentioned_columns: no

`update_attributes` is deprecated now on master, because it was confusing. 
Calling `update_attribute` on a record with unsaved changes is generally an 
antipattern, but its behavior is clearly documented.

> update_columns/update_column => callbacks: no, validations: no, setters: no, 
> touch: no, only_save_mentioned_columns: yes
> increment!/decrement!/toggle! => callbacks: no, validations: no, setters: no, 
> touch: no, only_save_mentioned_columns: yes
> increment!/decrement!(touch: true) => callbacks: no, validations: no, 
> setters: no, touch: yes, only_save_mentioned_columns: yes
> touch => callbacks: some, validations: no, setters: no, touch: yes, 
> only_save_mentioned_columns: yes

These are special-purpose methods and don’t belong in this list, IMO.

> update_all/Class update => callbacks: no, validations: no, setters: no, 
> touch: no, only_save_mentioned_columns: yes

These last two aren’t the same - the former generates a single UPDATE query, 
but the latter loads each object and calls `update`. This may count as evidence 
for your point about  “need[ing] to double check which does what” above. :)


> Proposal A: 
> 
> Follow what the `save` pattern started, and provide explicit instructions to 
> update, and a more complete list to save
> 
> 1. Add `callbacks: false` option to save.

Which callbacks run when you specify `callbacks: false, validate: true`? In 
particular, does this skip `before_validation`/`after_validation`?

IMO if you’re skipping callbacks on a generic call to `save` you’ve got 
callbacks that might not really be callbacks.

> 2. Add `validate:`,`touch:`,`callbacks:`,`only_save_mentioned_columns:` to 
> update, with the option of providing the instructions in a separate hash for 
> models where those are columns/attributes
> e.g. `update(column: whatever, callbacks: false)`, or `update(**params, 
> callbacks: false)` or `update({ column: whatever }, callbacks: false)`, or 
> `update(params, callbacks: false)`

Not a fan of taking this many boolean flags.

> 6. validate the keyword arguments passed to save/update, so people don't 
> accidentally write 'skip_callbacks: true' or 'validates: false' or etc

This is the best suggestion in this proposal IMO, but it’s hard to do since the 
flags are consumed by different parts of the `save` method implemented in 
different files.

> Proposal B:
> 
> Rather than modifying update_*/save signatures, deprecate and replace with a 
> method called `persist` and `persist!` that takes those options

IMO if Proposal B was the status quo, we’d be talking about giving 
frequently-used combinations of those boolean flags specific names like 
“update_column” and deprecating `persist`.

To sum up:

* the only things that currently skip callbacks are specialized methods 
explicitly intended to do very limited updates to the DB. IMO this shouldn’t 
change

* similarly for `only_save_mentioned_columns`; only the specialized methods 
skip saving dirty columns

* `validate` and `touch` are already boolean options to `save`. They aren’t 
available in `update`, but `update` is literally just “assign attributes and 
call save” so IMO it’s trivial to get a similar result if needed.

* in conclusion, I don’t see how exposing more of the internal implementation 
as controllable options *reduces* the need to understand the internals

Re: [Rails-core] [Feature] Symbol to_proc coercions: Enumerable#map can take several symbols

2018-05-16 Thread Matt Jones

> On May 11, 2018, at 1:10 PM, Alberto Almagro <albertoalma...@gmail.com> wrote:
> 
> These days I have been comparing records in my daily job lots of times, which 
> made me think about a better way to retrieve and compare them. When I want to 
> navigate through several relations in a collection I often see myself writing 
> code like the following:
> 
> Given orders as a collection of Order:
> > orders.map(&:order_option).map(&:item).map(&:title)
> => ['Foo', 'Bar', 'Baz']
> 
> That is, chaining maps with Symbol to Proc coercions one after each other. 
> Sharing my thoughts with my company's architect we came up with the 
> alternative:
> > orders.map { |order| order&.order_option&.item&.title }
Very small nitpick: the code above (which tolerates `nil`) isn’t equivalent to 
the chained map (which doesn’t). But anyways...


> But we agreed that the notation was awful and didn't improve what we had 
> before. With this, I proposed what I think it is more like what we would 
> expect Ruby to have. I would like to add a notation similar to the one we can 
> find at Array#dig <https://ruby-doc.org/core-2.5.0/Array.html#method-i-dig> 
> or Hash#dig <https://ruby-doc.org/core-2.5.0/Hash.html#method-i-dig> in the 
> following manner:
> > orders.map(&:order_option, &:item, &:title)
> The method doesn't necessarily need to be named map or collect, we can agree 
> on a different name for it if you want. Please share your thoughts with me. 
> If you like this, I would be very happy to write a PR to include it in Rails.

This reminds me of the Elixir function `get_in` and the associated functions in 
`Elixir.Access`. I’m not sure if any of the existing methods would make sense 
to extend with the behavior, though:

* `dig` is called on a collection and returns one element with many levels of 
nesting
* `pluck` is called on a collection and returns a collection, but only at one 
level of nesting
* the proposed function is called on a collection and returns a collection, 
with many levels of nesting

Neither function can guarantee that its arguments are scalars (or even that 
they aren’t Procs, for that matter) so extending them is tricky. Probably 
better to pick a new name.

You might also consider “Proc#*” from Facets:

https://github.com/rubyworks/facets/blob/master/lib/core/facets/proc/compose.rb

I haven’t tried it, but in principle this should work if the operator 
precedence goes correctly:

orders.map(&:order_options * &:item * &:title)

—Matt Jones

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at https://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


Re: [Rails-core] getting AR to do postgres jsbonb atomic updates

2018-03-05 Thread Matt Jones

> On Mar 3, 2018, at 3:47 PM, Jonathan Rochkind <jonat...@dnil.net> wrote:
> 
> It is now easy to store a hash serialized as jsonb in posgres.  It is even 
> pretty easy with store_accessor to make individual keys in the hash look like 
> separate attributes. 
> 
> But when AR decides the jsonb column needs to be updated, it will send the 
> entire hash as an update value.  If you only changed a key or two, it will 
> still send the entire hash -- possibly overwriting changes to other keys made 
> by other processes/clients. 
> 
> Recent versions of postgres supports an atomic update on just certain keys of 
> a jsonb hash, using `jsonb_set` in SQL. 
> 
> I'd like to explore trying to get AR to do this, at first with a plugin.  
> With dirty tracking, it's fairly straightforward for AR to figure out what 
> top-level keys have been changed and what haven't. 
> 
> But I can't quite figure out where to intervene in AR to change the SQL 
> generated in an 'update' operation. So I can generate different SQL that will 
> do an atomic update, where possible. 

The most central spot would be in `_update_record`:

https://github.com/rails/rails/blob/263f01d93da118dc150c6ac816e70dcf10de2608/activerecord/lib/active_record/persistence.rb#L195
 
<https://github.com/rails/rails/blob/263f01d93da118dc150c6ac816e70dcf10de2608/activerecord/lib/active_record/persistence.rb#L195>

or in the related `_substitute_values` method.

This could be too late to see things like dirty tracking, though - you may need 
to start searching up the call stack from `_update_record`.

—Matt Jones

> If anyone could give me any advice on where might work to hook into AR to 
> change generated SQL for 'update', I would appreciate it!  And I hope to look 
> into making a plugin to let AR do specified-key-only updates to postgres 
> jsonb columns. Thank you for any advice!
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Ruby on Rails: Core" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to rubyonrails-core+unsubscr...@googlegroups.com 
> <mailto:rubyonrails-core+unsubscr...@googlegroups.com>.
> To post to this group, send email to rubyonrails-core@googlegroups.com 
> <mailto:rubyonrails-core@googlegroups.com>.
> Visit this group at https://groups.google.com/group/rubyonrails-core 
> <https://groups.google.com/group/rubyonrails-core>.
> For more options, visit https://groups.google.com/d/optout 
> <https://groups.google.com/d/optout>.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at https://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


Re: [Rails-core] Master thesis on Rails

2018-02-14 Thread Matt Jones
HTTP2 Early Hints are shipping in 5.2.0, which is currently in RC.

More details: http://eileencodes.com/posts/http2-early-hints/ 
<http://eileencodes.com/posts/http2-early-hints/>

—Matt Jones

> On Feb 11, 2018, at 5:54 AM, utilum <oz.shel...@gmail.com> wrote:
> 
> What is the status on HTTP 2 ?
> 
> On Thursday, February 25, 2016 at 5:44:18 PM UTC+1, Arthur Neves wrote:
> Http 2 Is something that pops into my mind when I think something I would 
> like to see in Rails. I know Aaron P. was working on it, but not sure how far 
> he got.
> 
> On Thu, Feb 25, 2016 at 10:59 AM Luís Ferreira <lu...@zamith.pt 
> > wrote:
> Hi everyone,
> 
> This year my company (https://subvisual.co/ <https://subvisual.co/>) will 
> have a student doing his master thesis with us, and need to come up with a 
> topic. I was wondering if there was anything on Rails tangentially related to 
> his areas of expertise that could benefit from a person working on it 
> essentially full time for 6 months or more, for free.
> 
> He's mastering on both distributed systems and parallel computing, as well as 
> Internet of Things and biometric systems. He already has a good familiarity 
> with Ruby and Rails.
> 
> So, I'd like to know:
> 
> 1. Is there any specific part of rails or feature to be implemented that he 
> could work on?
> 2. Is anyone on the core team interested in getting involved with helping him 
> out?
> 
> Best,
> Luis Zamith
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Ruby on Rails: Core" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to rubyonrails-co...@googlegroups.com .
> To post to this group, send email to rubyonra...@googlegroups.com 
> .
> Visit this group at https://groups.google.com/group/rubyonrails-core 
> <https://groups.google.com/group/rubyonrails-core>.
> For more options, visit https://groups.google.com/d/optout 
> <https://groups.google.com/d/optout>.
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Ruby on Rails: Core" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to rubyonrails-core+unsubscr...@googlegroups.com 
> <mailto:rubyonrails-core+unsubscr...@googlegroups.com>.
> To post to this group, send email to rubyonrails-core@googlegroups.com 
> <mailto:rubyonrails-core@googlegroups.com>.
> Visit this group at https://groups.google.com/group/rubyonrails-core 
> <https://groups.google.com/group/rubyonrails-core>.
> For more options, visit https://groups.google.com/d/optout 
> <https://groups.google.com/d/optout>.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at https://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


Re: [Rails-core] Change where module file goes for namespaced AR models

2017-10-19 Thread Matt Jones

> On Oct 18, 2017, at 3:56 PM, Matt Wire <mattw...@kidstark.com> wrote:
> 
> Hello all!
> 
> Because Rails apps get cluttered up rather quickly, I am proposing a change 
> to this Rails generator method:
> 
> https://github.com/rails/rails/blob/master/activerecord/lib/rails/generators/active_record/model/model_generator.rb
>  (starting at LOC 29)
> 
> def create_module_file
>   return if regular_class_path.empty?
>   template "module.rb", File.join("app/models", "#{class_path.join('/')}.rb") 
> if behavior == :invoke
> end
>   
>   
> 
> TO
> 
> Enter co
> def create_module_file
>   return if regular_class_path.empty?
>   template "module.rb", File.join("app/models", class_path, 
> "#{class_path.join('/')}.rb") if behavior == :invoke
> end
> de here...
> 
> 
> Some more background and argument:
> 
> when you do something like:
> rails g model admin/dashboard
> rails g model user/dashboard user/profile
> 
> You'll get nicely namespaced AR models and tables. The AR models are placed 
> into a sub-directory within the models directory and a module is placed into 
> the root model directory. The module only contains the table_name_prefix. So 
> why not put that module into the sub-directory with the model(s)?

For concreteness, are you suggesting that the first command there generate the 
file at `app/models/admin/admin.rb`? AFAIK that’s not going to work with the 
existing autoloader - it won’t look there by default, and it would expect a 
file located there to define a class or module named `Admin::Admin` if it did.

—Matt Jones

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at https://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


Re: [Rails-core] Break out testing library from ActiveSupport?

2017-08-02 Thread Matt Jones

> On Jul 25, 2017, at 4:00 PM, Jaco Pretorius <jdjpretor...@gmail.com> wrote:

> On Thursday, January 9, 2014 at 4:08:34 PM UTC-5, Steve Klabnik wrote:
> Minitest is already in the standard library, so you're not really 
> adding or removing any meaningful dependence. 

> I just found this thread after noticing the same dependency today and looking 
> for a way to potentially remove this. I don't quite see a dependency on 
> minitest in the 'standard library' (by which I assume you mean the Rails gem 
> itself).  https://github.com/rails/rails/blob/master/rails.gemspec  Or is 
> there another dependency I'm missing?
> 

When Steve wrote that sentence three+ years ago, minitest was still included as 
part of the Ruby standard library. It was removed in 2.2 - see this discussion 
for more details:

https://bugs.ruby-lang.org/issues/9711

> As far as I can tell we would need to not autoload test_case.rb and then wrap 
> the 'require' call to give a more meaningful error.  It's not clear to me if 
> we expect consumers of the gem to use the ActiveSupport::TestCase class, or 
> is that purely for testing the library itself?  I don't see any explicit 
> examples for it in the documentation, but I'm also not that familiar with 
> MiniTest.

ActiveSupport::TestCase can be used directly (see the example in the guides: 
http://guides.rubyonrails.org/testing.html#rails-meets-minitest 
<http://guides.rubyonrails.org/testing.html#rails-meets-minitest> ). The 
minitest plumbing is also used by Rspec (in at least some cases):

https://github.com/rspec/rspec-rails/blob/e8054a1cd03044f725030fe8315952cf3799a395/lib/rspec/rails/adapters.rb#L22
 
<https://github.com/rspec/rspec-rails/blob/e8054a1cd03044f725030fe8315952cf3799a395/lib/rspec/rails/adapters.rb#L22>

I’ll reiterate Rafael’s point from earlier in the thread: why is removing this 
dependency important?

—Matt Jones

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at https://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


Re: [Rails-core] Provide all ActiveRecord exceptions with a `record` attribute

2016-12-02 Thread Matt Jones

> On Dec 1, 2016, at 6:07 PM, Wael Khobalatte <wael.khobala...@gmail.com> wrote:
> 
> Hey, 
> 
> It would be useful to inspect the record in question every time an 
> ActiveRecord exception is raised. This is currently possible with some 
> (ActiveRecord::RecordNotSaved for instance), but not others. Any idea what 
> the rationale for this selection is? I initially thought that you can query 
> the exception for the record as long as it exists (or existed), but 
> ActiveRecord::RecordNotSaved refutes that assumption, because you could be 
> creating it for the first time. 
> 
> The goal from such a proposal would be generic error collecting. For instance 
> rescuing from all descendants of ActiveRecordError and passing the record id 
> to Sentry, if it exists. But so far it won't work with all of them 
> 
> Not sure if it helps, but I was initially interested in the record associated 
> with a StatementInvalid exception.

This seems tricky - many of the places where StatementInvalid (or its 
descendants) is raised don’t have any direct relationship with a particular 
record. For instance, an ActiveRecord::InvalidForeignKey could occur in an 
`update_all` call - or an ActiveRecord::PreparedStatementCacheExpired could 
happen on a query.

The children of ActiveRecordError that currently include a record are much more 
directly tied to the concept “the code specifically requested that X be done to 
*this* object but something went wrong” (RecordNotSaved, RecordNotDestroyed, 
StaleObjectError, UnknownAttributeError) than the situations that raise 
StatementInvalid.

—Matt Jones

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at https://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


Re: [Rails-core] Warn the developer when using `to:` with an array of emails that he is going to reveal the emails to everyone

2016-10-13 Thread Matt Jones

> On Oct 7, 2016, at 12:29 AM, Brian Morearty <br...@morearty.org> wrote:
> 
> > Ideally testing would have brought the "error" to your attention before it 
> > was used in production.
> 
> I think the point here was that the coder did not think if this problem. 
> Adding a test for it would require thinking if it.
> 

My parsing of the previous statement was that *manual* testing could have 
caught this - basic, “push the button and see what it does” kind of testing.

I don’t see the utility of a guardrail to prevent “bad” emails from being 
generated: people who understand the risks end up having to do a slight amount 
of additional ceremony, and people who don’t understand the risks copy-paste 
the incantation to “make it work”.

—Matt Jones

> I do think it would be strange for bcc to be the default, though. The only 
> alternative I can think of would be a small breaking change: if multiple 
> recipients would be able to see each others' emails, require setting an 
> `allow_recipients_to_see_each_others_emails` flag. If not set, and multiple 
> recipients are on to/cc, raise an error. 
> 
> I'm not sure how good or bad this would be. 
> 
> 
> 
> 
> On Thursday, October 6, 2016, Andrew Kaspick <akasp...@gmail.com 
> <mailto:akasp...@gmail.com>> wrote:
> I don't think anything should be changed to deal with the api personally.  
> The options translate to how email works and to me that's what makes the most 
> sense.  Ideally testing would have brought the "error" to your attention 
> before it was used in production.
> 
> On Thu, Oct 6, 2016 at 7:42 AM, <jeremy.fr...@projets2coeur.fr 
> <javascript:_e(%7B%7D,'cvml','jeremy.fr...@projets2coeur.fr');>> wrote:
> Hi there,
> 
> I've just made this mistake of sending an e-mail to a few hundred people, 
> revealing their emails to everyone else.
> 
> Usually we loop over the users and send a personalized email to each one of 
> them, but for once the email was the same so I went with sending it once.
> That's why I did not even think about the fact that the emails would be 
> visible to everyone.
> The "fun" part of it is that I thought I was so clever to enhance performance 
> by sending it only once.
> 
> Anyway, after having thought about my mistake I realized that most of the 
> time when sending the same email to a bunch of people one would almost never 
> want the emails to be visible to everyone.
> The exception would be to allow people to reply to one another, like in some 
> task management system, but again I think in the majority of cases one 
> wouldn't want that.
> 
> That's why I think it's best to be cautious by default, maybe by doing a BCC 
> send by default unless some other option is provided (`reveal_emails: true` 
> ?).
> I think it would be a safe bet because if I'd like others to see the emails I 
> most probably will notice while working on the feature that they are not 
> visible by default.
> The opposite is not true. Proof is I just totally forgot about this 
> "side-effect".
> 
> What do you guys think ?
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Ruby on Rails: Core" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to rubyonrails-core+unsubscr...@googlegroups.com 
> <javascript:_e(%7B%7D,'cvml','rubyonrails-core%2bunsubscr...@googlegroups.com');>.
> To post to this group, send email to rubyonrails-core@googlegroups.com 
> <javascript:_e(%7B%7D,'cvml','rubyonrails-core@googlegroups.com');>.
> Visit this group at https://groups.google.com/group/rubyonrails-core 
> <https://groups.google.com/group/rubyonrails-core>.
> For more options, visit https://groups.google.com/d/optout 
> <https://groups.google.com/d/optout>.
> 
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Ruby on Rails: Core" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to rubyonrails-core+unsubscr...@googlegroups.com 
> <javascript:_e(%7B%7D,'cvml','rubyonrails-core%2bunsubscr...@googlegroups.com');>.
> To post to this group, send email to rubyonrails-core@googlegroups.com 
> <javascript:_e(%7B%7D,'cvml','rubyonrails-core@googlegroups.com');>.
> Visit this group at https://groups.google.com/group/rubyonrails-core 
> <https://groups.google.com/group/rubyonrails-core>.
> For more options, visit https://groups.google.com/d/optout 
> <https://groups.google.com/d/optout>.
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Ruby on Rails: Core" group.
&

Re: [Rails-core] Using "IS DISTINCT FROM" instead of "!=" for inequality checks

2016-03-19 Thread Matt Jones

> On Mar 16, 2016, at 3:03 PM, Jeremy McNevin <jmcne...@gmail.com> wrote:
> 
> I'd be interested in hearing thoughts about changing the generated SQL for a 
> negated equality comparison from using "!=" to "IS DISTINCT FROM" (where 
> supported), since the latter has less-surprising handling of NULL values.
> 
> For example, with the following bit of AR:
> 
> User.where.not(parent_id: 10)
> 
> You would get some SQL roughly equivalent to:
> 
> WHERE parent_id != 10
> 
> But this would not return rows where parent_id is NULL, since a comparison 
> against NULL always returns NULL.  This SQL would behave as we'd expect:
> 
> WHERE parent_id IS DISTINCT FROM 10
> 
> Would there be any disadvantages to doing this sort of comparison by default?

It’s definitely additional effort, as `IS DISTINCT FROM` is not supported by 
all the default adapters:

* PostgreSQL supports it

* SQLite doesn’t support it, but has the similar-in-function `IS NOT` operator.

* MySQL doesn’t support it - and has an `IS NOT` operator, but it means 
something different (and only accepts TRUE / FALSE / UNKNOWN as a right-hand 
argument)

* Oracle doesn’t support it, or have a similar operator. (based on my limited 
reading of the Oracle docs)

Those last two would need a fallback (something like `parent_id != 10 OR 
parent_id IS NULL`). The change would be pretty straightforward - just tweak 
the DB-specific visitors in Arel.

I suspect the most difficult work for a change like this would be coordinating 
& messaging the update - it would need to be announced quite prominently, since 
the change will result in queries returning different results while still 
succeeding.

—Matt Jones


-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at https://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


Re: [Rails-core] link_to_if/link_to_unless inconsistencies

2015-11-05 Thread Matt Jones
On Thu, Nov 5, 2015 at 9:26 AM, Kevin Deisz <kevin.de...@gmail.com> wrote:

> Hi there,
>
> Seems like in the positive condition, link_to_if and link_to_unless are
> inconsistent. When I send a block to link_to (or for that matter anything
> else that calls content_tag) the block is used to determine the content in
> the case that "name" is not provided. It gets around this by shifting the
> args, effectively, as in (html_options, options, name = options, name,
> block if block_given?).
>
> However, with link_to_if/link_to_unless, when the condition is met it
> always uses the main content. As in:
>
> link_to_if(true, root_path) do
>   My Link <%= some_helper %>
> end
>
> looks like "/" in the UI and the block is ignored. I'd love to fix this,
> but want to make sure there isn't some good reason first.
>
>
In this use case, how would one specify the content to be used if the
condition is `false`?

I can't think of a way that isn't clunkier than the plain ERB way to
accomplish the same thing:

<% if condition %>
  <%= link_to foo_path do %>
Content for true
  <% end %>
<% else %>
  Content for false
<% end %>

IMO, `link_to_if` and `link_to_unless` are intended to capture a common
pattern that would otherwise lead to repeated strings / code. If you need a
behavior that's well outside of that pattern, just write ERB / helpers /
etc.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


Re: [Rails-core] has many :through using defined scopes from the :through association instead of dupping

2015-10-16 Thread Matt Jones
On Thu, Oct 15, 2015 at 9:17 PM, Will Spurgin <will.spur...@gmail.com>
wrote:

> Hey all,
>
> I've been doing a *bunch* of researching on this topic, and I wanted to
> get feedback from the community on this potential feature (or if I'm just
> completely missing that it's already a feature, your gentle correction).
>
> Recently, I've started a project, and I ran across a scenario where I had
> to introduce duplicate scoping while defining an association. :(
>
> Here's a summary of the scenario: There is one model that has one scope
> and two associations to two other models. In one of the other models that
> the first "joining" model is associated with, I have a has_many association
> through this joined model. However, the complication (and duplication
> arises) that the association has to be scoped to the scope on the joining
> model. Currently (from what I've found through research), there's no way to
> specify an *existing scope* on a :through association. The workaround is
> to create a scope on the has_many association that does the exact same
> thing that the :through association's scope already does.
>
> An example will probably help illuminate the problem:
>
> Assume we have the following models definitions:
>
> class Book < ActiveRecord::Base
>   belongs_to :author,inverse_of: :books
>   belongs_to :publication, inverse_of: :books
>
>   scope :published, -> { where(is_published: true) }
>
>   # ...
> end
>
>
> class Author < ActiveRecord::Base
>   has_many :books, inverse_of: :author
>   has_many :publications, -> { where(books: { is_published: true }) },
> through: :books
>
>   # ...
> end
>
>
> class Publication < ActiveRecord::Base
>   has_many :books, inverse_of: :publication
>
>   # ...
> end
>
>
> Notice the has_many :through association; this is currently how you'd have
> to *manually scope* the "publications" association to achieve the same
> effect of :
> publications = books.published.map(&:publication)
>
> I'd *like* to write something similar to:
> has_many :publications, through: { :books => :published }
>
>
>
I'd handle this with a specifically-named association (in `Author`):

has_many :published_books, -> { published }, class_name: 'Book'
has_many :publications, through: :published_books

You may also want to look into the documentation for the `merge` method on
Relation.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


Re: [Rails-core] ActiveRecord connection pool management

2015-10-01 Thread Matt Jones
If the concern is long-running threads holding DB connections they don't
need, wouldn't a simpler solution be to explicitly return connections to
the pool (via release_connection) before doing a long-running non-DB
operation? Checking out and back in on most operations seems like
optimizing for that uncommon case at a runtime cost for the common one.

--Matt Jones

On Thu, Oct 1, 2015 at 4:25 AM, Xavier Noria <f...@hashref.com> wrote:

> The only time I've seen one connection per thread being an issue was in
> one app that ran many processes and it started to reach the connection
> limit of their db server in traffic peaks. Even in that scenario,
> contention is also a risk if you reduce the pool.
>
> Other than the mental image that you're using less resources (at the price
> of contention), I am not sure there is going to be any significant
> practical win. It could be, I am not saying it wouldn't (I have not done
> your study), but at first sight the cost/benefit is not clear to me in
> practical terms.
>
> Regarding transactions, #execute is public AR interface, and
>
> AR::Base.connection.execute('START TRANSACTION')
>
> is valid AR code, I am not sure if drivers know the connection is in a
> transaction and have API to check, but #transaction_open? returns false as
> of this writing. Why would anybody do that? I don't know, maybe because
> they are writing a heavy SQL oriented script and doing that manually feels
> natural... it doesn't matter, it can be done.
>
> Another practical point is that when a connection is checked out the
> connection pool tests if it is alive issuing for example SELECT 1. That
> would mean that if a request performs today 200 queries, they would become
> 400 queries. I don't know if the alive check could be rethought to run less
> frequently, but it probably should to avoid that 2x.
>
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Ruby on Rails: Core" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to rubyonrails-core+unsubscr...@googlegroups.com.
> To post to this group, send email to rubyonrails-core@googlegroups.com.
> Visit this group at http://groups.google.com/group/rubyonrails-core.
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


Re: [Rails-core] ActiveRecord connection pool management

2015-10-01 Thread Matt Jones
On Thu, Oct 1, 2015 at 4:25 AM, Xavier Noria <f...@hashref.com> wrote:

> The only time I've seen one connection per thread being an issue was in
> one app that ran many processes and it started to reach the connection
> limit of their db server in traffic peaks. Even in that scenario,
> contention is also a risk if you reduce the pool.
>
> Other than the mental image that you're using less resources (at the price
> of contention), I am not sure there is going to be any significant
> practical win. It could be, I am not saying it wouldn't (I have not done
> your study), but at first sight the cost/benefit is not clear to me in
> practical terms.
>
> Regarding transactions, #execute is public AR interface, and
>
> AR::Base.connection.execute('START TRANSACTION')
>
> is valid AR code, I am not sure if drivers know the connection is in a
> transaction and have API to check, but #transaction_open? returns false as
> of this writing. Why would anybody do that? I don't know, maybe because
> they are writing a heavy SQL oriented script and doing that manually feels
> natural... it doesn't matter, it can be done.
>
> Another practical point is that when a connection is checked out the
> connection pool tests if it is alive issuing for example SELECT 1. That
> would mean that if a request performs today 200 queries, they would become
> 400 queries. I don't know if the alive check could be rethought to run less
> frequently, but it probably should to avoid that 2x.
>
>
Good point. That's an additional overhead, especially for systems with DBs
that are farther away.

One other point, possibly MySQL-specific: there are connection-specific SQL
variables. Under the current system, code can rely on them being set after
they are set in the same thread:

ActiveRecord::Base.connection.execute("SET SQL_MODE = ''")
# now SQL_MODE for the connection is set to empty string
SomeModel.create(...)

With per-DB-interaction checkin/checkout, it doesn't appear to be possible
to reliably manipulate these variables, as the connection used in the first
statement may not match the one used in the second. More amusing /
worrisome, somebody ELSE gets a connection with an altered SQL_MODE...

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


Re: [Rails-core] reset association cache for polymorphism

2015-09-20 Thread Matt Jones

On Sep 19, 2015, at 12:03 PM, Oto Iashvili <optimum.dulo...@laposte.net> wrote:

> Hi,
> 
> I have a product class with category and  a polymorphic attributes 
> details_info, that depending on category go to one or another table to get 
> the detail
> 
> 
> Class Product
> category
> details_info
> 
> end
> 
> Class DetailsInfo
> ...
> end
> 
> Class Pencil
> 
>   include DetailsInfo
> type
> color
> end
> 
> Class Notebook
> 
>   include DetailsInfo
> size
> ...
> end
> 
> and to display products i do
> prds = Products.all
> prds.each do |pr|
> 
> if pr.category == 'pencil'
> DetailsInfo.table_name = 'pencil'
> 
> else if pr.category == 'notebook'
> 
> DetailsInfo.table_name = 'notebook'
> end
> 
> end
> 
> (this is just kind of algo I use)
> 
> All this was working fine but with rails > 4.2 , it doesnt work anymore.
> The first time pr.details_info will be called, it seems that the table name 
> is cached somewhere, and then all other products are using the same 
> table_name. When I check during loop, I can see that DetailsInfo.table_name 
> is always correct, but still when pr.details_info will be called , it used 
> the first table_name that was used. I can also see that the method table_name 
> is called every step of the loop, and it return the good table_name, but 
> still, the sql request search on bad table.
> 
> How can I reset that ? Ive tried a lot a thing like emptying 
> association_cache, also different things with reflect_on_all_associations, 
> reset_column_information, reload, …

FWIW, you should take a look at the “Polymorphic Associations” section in the 
Guides: 
http://guides.rubyonrails.org/association_basics.html#polymorphic-associations 
My guess is that that functionality will allow you to avoid the `table_name` 
swapping that’s tripping up the code above.

But also note that this list is for development of the Rails framework, not for 
debugging individual applications. rails-talk is the correct place for this 
question.

—Matt Jones

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] Bug in HashWithIndifferentAccess?

2015-09-01 Thread Matt Jones

On Sep 1, 2015, at 6:29 AM, Yves-Eric <yemar...@gmail.com> wrote:

> Hi all,
> 
> 
> I think I have stumbled upon a bug in HashWithIndifferentAccess.
> I cannot pinpoint it exactly, but I have written a small test case that 
> exhibits the buggy behavior:
> 
> https://gist.github.com/yemartin/54db7476aa41b85e7eb8
> 
> The same code works fine if we use a regular Hash for `@store` instead of a 
> HashWithIndifferentAccess.
> Is this a known issue or should I fill a bug report?

This code in your example:

  @store[:foo] ||= {bar: 'BAR'}

does not do what you may be thinking it does. HWIA overrides the `[]=` operator:

https://github.com/rails/rails/blob/master/activesupport/lib/active_support/hash_with_indifferent_access.rb#L96

to convert incoming plain Hash objects into HWIA. So the object that eventually 
is stored in `@store[:foo]` is NOT the one that was passed to the assignment 
operator.

You can check this explicitly:


  require 'active_support/all'

  @store = ActiveSupport::HashWithIndifferentAccess.new

  def my_hash
@store[:foo] ||= {bar: 'BAR'}
  end

  first_time = my_hash # => {:bar =>”BAR”}
  second_time = my_hash # => {“bar”=>”BAR”}

Note that `first_time` and `second_time` don’t have matching `inspect` results. 

Assignment operators *always* return the value passed on the right-hand side, 
regardless of what the underlying `[]=` method returns. This means that in 
cases where the object doesn’t require conversion (coalwater’s modification 
from your Gist) the object returned from `||=` DOES match, and Waldo is found.

Not sure if there’s a fix for this - the converting-on-[]= behavior is 
something many applications are likely to depend on, and the behavior of 
assignment operators is a core Ruby issue.

—Matt Jones

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] Re: Always set id from database when creating new record

2015-08-24 Thread Matt Jones
On Fri, Aug 21, 2015 at 2:46 PM, masa331 do...@uol.cz wrote:

 I don't think it would. You set the id in model, it's passed to database,
 and then database returns it back again


Some of the database adapters require an additional round-trip to retrieve
the newly-inserted ID; this doesn't happen if an id was supplied at record
creation. Others (like MySQL) will fall back on the DB's built in last
inserted ID mechanism, which doesn't work if you are generating IDs
manually (`mysql_insert_id`, for instance, only gets a value if the id
column was AUTO_INCREMENT).

For more detail, keep tracing from where you quoted. `_create_record` calls
`ActiveRecord::Relation#insert`, here:

https://github.com/rails/rails/blob/337684fa28a3e8d55874d5740585710d0fa99ead/activerecord/lib/active_record/relation.rb#L41

which does two things:

* if the primary key is empty and the adapter wants to use prefetch, it
generates an ID

* explicitly selects the supplied (or generated) primary key value and
passes it as a separate argument to the `insert` method in the connection
adapter.

The default implementation of the connection adapter's `insert` method:

https://github.com/rails/rails/blob/337684fa28a3e8d55874d5740585710d0fa99ead/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb#L107

will automatically return the value passed in as `id_value`, if present.
The MySQL and Postgres versions appear to do this as well.

A workaround for your case would be database-specific; for instance, on
MySQL I'd recommend that you ensure the trigger sets `LAST_INSERT_ID` and
then extract the value from the DB directly (via `SELECT LAST_INSERT_ID()`)
in an `after_create`. Unfortunately, the ID is the one field that the
standard, DB-independent approach to dealing with trigger-supplied data
(calling `reload` after saving) won't work for. :)

--Matt Jones

Dne pátek 21. srpna 2015 17:26:49 UTC+2 masa331 napsal(a):

 Hi guys,

 this is code from ActiveRecord::Persistance:

 def _create_record(attribute_names = self.attribute_names)
 attributes_values = arel_attributes_with_values_for_create(
 attribute_names)
   new_id = self.class.unscoped.insert attributes_values   self.id ||=
 new_id if self.class.primary_key
   @new_record = false   id end

 I'm curious about the rational behind line no. 5. Why we set `self.id`
 to value returned from db only if it was previously empty? I couldn't find
 any test nor some discussion. Also the code dates back to 2011.

 I work with some legacy db where primary key is string which is modified
 in some database trigger. Because the `self.id` is set before save it
 isn't assigned to proper value returned from db after trigger modification.

 I can't think of any problem if we always assign id to value returned
 from database.

 I would love to create PR if it's ok

 thanks!

 Sledujte náš blog.uol.cz, facebook.com/uol.cz, gplus.to/uolcz
 http://facebook.com/uol.cz


 Sledujte náš blog.uol.cz, facebook.com/uol.cz, gplus.to/uolcz
 http://facebook.com/uol.cz

 --
 You received this message because you are subscribed to the Google Groups
 Ruby on Rails: Core group.
 To unsubscribe from this group and stop receiving emails from it, send an
 email to rubyonrails-core+unsubscr...@googlegroups.com.
 To post to this group, send email to rubyonrails-core@googlegroups.com.
 Visit this group at http://groups.google.com/group/rubyonrails-core.
 For more options, visit https://groups.google.com/d/optout.


-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


Re: [Rails-core] Cookie store and object instances in session behavior when instance class no longer exists

2015-07-16 Thread Matt Jones

On Jul 15, 2015, at 11:06 AM, Rodrigo Rosenfeld Rosas rr.ro...@gmail.com 
wrote:

 Today a colleague was playing in another branch trying the ruby-saml gem to 
 play with SAML. When he was back to the master branch all requests failed for 
 apparently no reason. This is related to this (it was trying to instantiate 
 some OneLogin class which doesn't exist in master):
 
 http://devblog.songkick.com/2012/10/24/get-your-objects-out-of-my-session/
 
 I just think that it's too bad on Rails part to simply crash when it's unable 
 to deserialize some value from the cookie. I noticed Rack would simply ignore 
 them and return nil in such cases:
 
 https://github.com/rack/rack/blob/1.6.4/lib/rack/session/cookie.rb#L66
 
 Why not doing the same in Rails?
 
 https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/middleware/cookies.rb#L420
 
 I ended up doing something like this in my application:
 
 Rails.application.config.action_dispatch.cookies_serializer = :marshal
 
 module RailsSerializerPatch
  protected
 
  def deserialize(name, value)
super
  rescue
puts Failed to deserialize session value for #{name}: #{value}
nil
  end
 end
 
 ActionDispatch::Cookies::EncryptedCookieJar.prepend RailsSerializerPatch
 ActionDispatch::Cookies::SignedCookieJar.prepend RailsSerializerPatch
 
 
 I tried to prepend to SerializedCookieJars module but it didn't work and I 
 have no idea why, but anyway...
 
 Maybe it would be even better to delete that key from the session whenever 
 such error happens.
 

IMO this isn’t a good default behavior. Silently deleting the key - and 
muttering to STDOUT is pretty close to “silent” - means that if this issue is 
hit in production unexpectedly it is basically invisible.

 Shouldn't Rails better handle such deserialization problems without crashing 
 the whole application on every request? For example, even if I enable Devise 
 sign-out through get requests the application would crash (respond with 500) 
 before having the opportunity to clear up any cookies…

In the general case, if the session can’t be cleanly deserialized there’s very 
little that can be done. A specific application can make the call to muddle 
through”, but that would be an unsafe default for some applications.

 Or maybe Rails could simply remove all cookies when an error happens due to 
 deserialization raising. Or at least make the desired behavior more easily 
 configurable. What do you think?

+1 to making it configurable.

—Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] Feature: Use self-replying exceptions in ActiveSupport::Rescuable.rescue_from

2015-05-15 Thread Matt Jones
On Fri, May 15, 2015 at 6:15 AM, Arnaud Rouyer josh.guth...@gmail.com
wrote:

 I'm using a library to handle error responses across five different API
 apps. To stop all processing, this library raises an error that is later
 rescued with `rescue_from`.

 Since DRY is important to me, I also want to avoid repeating the
 `rescue_from` call and its handler block in all five applications.
 Furthermore, if I someday decide to change the handler, I would need to
 update all five applications.

 Solution I've found is to extend my error class with a `to_proc` method
 that generates a proc handling the response in the controller (in this
 case: `render json: exception.reply`). I've patched rails to this end:
 `rescue_from` can now be called without a block handler, in which case the
 block handler will be the proc of the exception.

 Full diff patch with tests is here:
 https://gist.github.com/joshleaves/10de348b0e8b28863213

 I'm waiting for feedback before submitting the PR. Thanks =)


IMO, the more idiomatic way to handle this would be to have a concern that
sets up these rescues defined in your library, then include it into
controllers in the clients as needed. Something like this:

https://gist.github.com/al2o3cr/3e1c492af329add23f30

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


Re: [Rails-core] ActiveRecord::ProtectedModel

2015-04-27 Thread Matt Jones

On Apr 26, 2015, at 5:08 PM, Yannis Kolovos yannis.kolo...@gmail.com wrote:

 
 I would like to protect my model in production of of being deleted
 
 
 It would be nice if rails provide this functionality by default ?
 I don't know if there is a functionality like this already but for me its 
 something fundamental
 If there is i couldn't find nothing till now
 Of Course there is the soft delete but this is a different concept 
 I dont know if my concept its valid or not or whats the gotchas but why 
 protected_attributes and not protected_model?

If this is a thing you need to do for legal / regulatory requirements, 
overriding a couple methods is NOT going to be sufficient - someone could 
always use:

  ActiveRecord::Base.connection.execute(‘DELETE FROM protected_stuffs WHERE id 
= 42’)

to bypass all of those. If you really can’t allow a record to be deleted from 
that table, I’d suggest revoking that permission from the user your application 
connects to the database as.

—Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] Fallback image for Rail's video_tag

2015-03-30 Thread Matt Jones

On Mar 30, 2015, at 9:02 AM, Gabriel Sobrinho gabriel.sobri...@gmail.com 
wrote:

 Seems like you can do it using the poster option.
 

I believe Aaron is referring to putting an `img` tag inside the `video` 
element, to accommodate browsers that don’t understand `video` at all.

http://stackoverflow.com/questions/14616453/image-placeholder-fallback-for-html5-video

Setting a placeholder won’t help those browsers, since they don’t handle the 
tag at all.

—Matt Jones

 On Sunday, March 29, 2015 at 6:30:21 PM UTC-3, Aaron Cordovez wrote:
 It seems like there is no way to provide a fallback image with Rail's 
 video_tag. 
 
 Is there a specific reason that the method was created this way? 
 http://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html
 
 Has anyone else come across the need to use a fallback image when using 
 video_tag, or found a way to do it without using raw html? 
 
 
 
 -- 
 You received this message because you are subscribed to the Google Groups 
 Ruby on Rails: Core group.
 To unsubscribe from this group and stop receiving emails from it, send an 
 email to rubyonrails-core+unsubscr...@googlegroups.com.
 To post to this group, send email to rubyonrails-core@googlegroups.com.
 Visit this group at http://groups.google.com/group/rubyonrails-core.
 For more options, visit https://groups.google.com/d/optout.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] basE91 in Rails

2015-03-08 Thread Matt Jones

On Mar 6, 2015, at 5:18 PM, sivsushruth sivsushr...@gmail.com wrote:

 I was checking out 
 https://github.com/rails/rails/blob/master/activesupport/lib/active_support/xml_mini.rb#L152
  
 It has: TODO: Add support for other encodings
 
 So, I googled a bit and found this: http://base91.sourceforge.net/ 
 On initial investigation, this seems a pretty good alternative to base64
 
 I feel this might be of good value to a lot of developers.
 If you guys feel the same way, I will be more than happy to get started on 
 this.

Is there any evidence that base91 is used “in the wild”? References to it are 
very light on Google etc; for instance, Wikipedia only mentions it as an 
“external link” on the Ascii85 page.

It’s also going to be tricky to embed in XML, since it uses several characters 
that XML reserves (, ,  and ) which will require escaping. That appears to 
have been addressed in a variant (https://github.com/r-lyeh/base91) which uses 
a different set of characters.

—Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] How does ActiveRecord::TestFixtures::ClassMethods#run_in_transaction? work?

2015-03-08 Thread Matt Jones

On Mar 6, 2015, at 12:59 AM, Brandon Weiss bran...@anti-pattern.com wrote:

 Here's the method:
 
 def run_in_transaction?
   use_transactional_fixtures 
 !self.class.uses_transaction?(method_name)
 end
 
 I'm super confused. What is `method_name`? And where does it come from? It's 
 not a local variable. I can find two instances of `def method_name` in the 
 repo and neither seem to be related. If I try to call the method directly and 
 `use_transactional_fixtures` is false I get `NameError: undefined local 
 variable or method `method_name'`. How is this working normally?

`ActiveRecord::TestFixtures` is mixed into the test case class itself. 
`method_name` is an alias for the `Test::Unit::TestCase#name` method, which the 
test harness sets up every time an individual test is started up.

The data maintained by `uses_transaction?` and friends is used to tell the 
fixture system that a particular test uses transactions internally 
(after_commit hooks, etc) and therefore *shouldn’t* be wrapped with a 
transaction. You’d specify this by saying `uses_transaction 
:name_of_test_that_uses_transactions` in your test case.

—Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] find_by inconsistent return message

2015-02-09 Thread Matt Jones

On Feb 8, 2015, at 11:07 AM, Иван Бишевац ivan.bise...@gmail.com wrote:

 User.find(1)
 for no record with gives:
 
 def test_error_message
   begin
 User.find(1)
   rescue ActiveRecord::RecordNotFound = e
 message = e.message
   end
 
   assert_equal message, Couldn't find User with 'id'=1
 end
 
 
 I expected same behavior wiht find_by! method but it doesn't give so 
 descriptive message.
 For example expected behavior should be:
 
 def test_error_message_for_find_by!
   begin
 User.find_by(first_name: 'foo', last_name: 'bar')
   rescue ActiveRecord::RecordNotFound = e
 message = e.message
   end
 
   assert_equal message, Couldn't find User with 'first_name'='foo' and 
 'last_name'='bar'
 end
 
 but it doesn't work like this instead e.message is just general Couldn't 
 find User”.

See also discussion on this PR:

https://github.com/rails/rails/pull/15791

and the related issue:

https://github.com/rails/rails/issues/15792

—Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] To Patch or Not To Patch

2015-02-05 Thread Matt Jones

On Feb 5, 2015, at 8:35 AM, Magne magn...@gmail.com wrote:

 I'd find it extremely useful. The current implementation sucks, for various 
 reasons.
 
 Actually, what you expect when you use distance_of_time_in_words, and what 
 arguably should be the default in rails, is for it to output precisely what 
 you input.
 The method is not called rounded_distance_of_time_in_words, after all.
 
 What you would expect:
 
 helper.distance_of_time_in_words(1.hour) = 1 hour  not about 1 
 hour which it currently does.
 helper.distance_of_time_in_words(1.hour+ 15.minutes) =   1 hour and 15 
 minutes or one hour and a quarter.  and not about 1 hour which it 
 currently does.
 
 Fancy rounding of hours and days should be something extra, for the people 
 that need that. 

Which, presumably, would be *everybody* who is using this helper now.

 For everyone else, there should be sane defaults, namely a convention that 
 doesn't violate expectation.
 You shouldn't have to monkey-patch the app, or use an extra gem, to get the 
 sane defaults.

You brought a 5+-year-old thread back to life to insist that the current 
behavior is not “sane”. [citation needed]
 
 Currently, this is how fancy it has become:
 
 helper.distance_of_time_in_words(41.hours+ 59.minutes+29.seconds) = 1 day  
 eh.. WTF?  Since when did 1 day become 42 hours and not 24? Even 
 according to the rounding principles used, this doesn't make much sense.
 
 Or these intervals:
 
 1 yr - 1 yr, 3 months   # 
 = about 1 year
 1 yr, 3 months - 1 yr, 9 months # 
 = over 1 year
 
 Who on earth would be able to deduce from the output that 1 year and 3 months 
 is about one year, and not over 1 year?
 
 See all the fancy roundings here in the docs, and see if you don't agree with 
 me.
 
 Having the expected precision is especially important when using this in 
 email communication towards users, or for communicating deadlines.
 Precision doesn't hurt, apart from being a bit UX unfriendly at times. On the 
 other hand, imprecision and fancy roundings can be very damaging.
 
 I vote that the relevant parts of the dotiw gem be made a part of core rails, 
 since the default behavior should be intuitive and straightforward. 

Make a PR then. Nobody has done it in the last 5 years, so I’m unconvinced it 
is a thing anyone wants.


 ---
 If you really find the fancy roundings useful, leave it in rails, but rename 
 it to rounded_distance_of_time_in_words, fix the bugs, 
 and update it to support atleast half-hours, half-days and so on. Like this:
 

I dunno who “you” is in the sentence above. If it bugs you this much, again, 
submit a PR for discussion. You’ll need to explain why you want to make a 
breaking change in every app that uses a function that hasn’t changed in years, 
and you’ll need to provide a patch to deprecate the old names in the next 4.x 
series release.

—Matt Jones


 helper.distance_of_time_in_words(1.hour+ 29.minutes) =   one and a half 
 hour or one hour and a half.  and not about 1 hour which it 
 currently gives
 
 There is already established a precedence for including halves. It currently 
 supports half-minutes:
 helper.distance_of_time_in_words(0, 39.seconds, include_seconds: true) = 
 half a minute
 
 ---
 
 cheers,
 
 Magne Gåsland
 
 fredag 7. august 2009 07.44.11 UTC+2 skrev Ryan Bigg følgende:
 Recently a lot of people I've spoken with have expressed that 
 distance_of_time_in_words sucks for accuracy, providing values such as about 
 2 years where 2 years, 5 months, 3 days, 4 hours, 6 minutes and 42 seconds 
 is more appropriate. To fix this, I've written a plugin: 
 http://github.com/radar/dotiw. I'm thinking that this should be in Rails core 
 as it is a vast improvement over what currently exists, but I don't want to 
 put the effort into a patch that's just going to be rejected, as per usual.
 
 Who else would find this useful?
 
 -- 
 Ryan Bigg
 
 -- 
 You received this message because you are subscribed to the Google Groups 
 Ruby on Rails: Core group.
 To unsubscribe from this group and stop receiving emails from it, send an 
 email to rubyonrails-core+unsubscr...@googlegroups.com.
 To post to this group, send email to rubyonrails-core@googlegroups.com.
 Visit this group at http://groups.google.com/group/rubyonrails-core.
 For more options, visit https://groups.google.com/d/optout.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] Generating ActiveRecord model table name to include namespace

2015-02-03 Thread Matt Jones
This will be a pretty rough default for some DBs that have short identifier 
maximums (Oracle is *30* characters).

We’d also need to be explicit about what happens with models that descend from 
namespaced classes (from an engine, for instance). IIRC, current behavior 
derives the table name for subclasses from the direct descendant of AR::Base.

—Matt Jones

On Feb 3, 2015, at 4:52 AM, Matthew Dunbar m...@mattdsworld.com wrote:

 Suggesting that we can auto generate the prefix based on the module name, 
 rather than setting it with the existing method. Then eventually this feels 
 like a sensible default to me.
 
 On Sunday, February 1, 2015 at 7:39:58 AM UTC-5, Carlos Antonio da Silva 
 wrote:
 Not sure I get what's the actual difference between a new option like that 
 and setting the table name prefix on the module, which will work for all 
 classes under it? Can you expand on that a bit?
 
 On Sat, Jan 31, 2015 at 4:52 AM, Matthew Dunbar ma...@mattdsworld.com wrote:
 I will implement this myself, looking for feedback on if it'd be accepted and 
 how the community feels about the long term of this being enabled by default.
 
 I often run into conflicts between table names when running multiple fairly 
 heavyweight engines that all deal with e-commerce (and in turn many have 
 tables such as most recently payments that conflict). The current solution is 
 to manually specify the table prefix in the appropriate gem / module.
 
 I am suggesting that we add a inherits_prefix_from_namespace flag to models, 
 then eventually in the long term (perhaps rails 5) defaulting this to be 
 enabled.
 
 Ideally this would work as follows:
 
 module Example
   module Widgets
 class Test  ActiveRecord::Base
   inherits_table_prefix_from_namespace: true
 end
   end
 end
 
 Rather than having its table name be tests , the table name would be 
 example_widgets_tests.
 
 In the case that a prefix is specified, the table name would be 
 prefix_example_widgets_tests (rather than prefix_tests).
 
 
 -- 
 You received this message because you are subscribed to the Google Groups 
 Ruby on Rails: Core group.
 To unsubscribe from this group and stop receiving emails from it, send an 
 email to rubyonrails-co...@googlegroups.com.
 To post to this group, send email to rubyonra...@googlegroups.com.
 Visit this group at http://groups.google.com/group/rubyonrails-core.
 For more options, visit https://groups.google.com/d/optout.
 
 
 
 -- 
 At.
 Carlos Antonio
 
 -- 
 You received this message because you are subscribed to the Google Groups 
 Ruby on Rails: Core group.
 To unsubscribe from this group and stop receiving emails from it, send an 
 email to rubyonrails-core+unsubscr...@googlegroups.com.
 To post to this group, send email to rubyonrails-core@googlegroups.com.
 Visit this group at http://groups.google.com/group/rubyonrails-core.
 For more options, visit https://groups.google.com/d/optout.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] Graceful handling of missing STI constants

2015-01-25 Thread Matt Jones

On Jan 25, 2015, at 3:42 PM, Maxim Chernyak madfanc...@gmail.com wrote:

 When using STI, if you introduce a new subclass in a git branch, then create 
 a db record while in it, then switch to another branch, you will get 
 uninitialized constant error when trying to query those records. Certain 
 kinds of applications (like ours) could run into this a lot, so I'm wondering 
 if there could be a null-object-patternish solution to this. E.g:
 
 * Accept proc for inheritance_column, which evaluates on instances, with type 
 passed as an arg to it, and whatever it returns becoming the record in that 
 case. This way we can plug those records with some placeholders

The proc can’t be run on an instance - the error is arising when AR tries to 
determine what class to use. The calling context is in find_sti_class:

https://github.com/rails/rails/blob/6d72485b6977804a872dcfa5d7ade2cec74c768e/activerecord/lib/active_record/inheritance.rb#L169

a class method defined on ActiveRecord::Base. At runtime, this will have access 
to the class that `find` was called on (presumably the STI base class) and the 
value from the inheritance column.

Returning a fully-initialized object from here would require skipping a bunch 
of code in `instantiate`.

 * Add option self.ignore_unknown_types = true to activerecord to simply 
 auto-rescue + skip records with uninitialized constant error (perhaps print a 
 warning instead)

It’s not clear to me what “skipping” a record in this scenario would mean. If I 
have a model that belongs_to an instance of the missing class, what do I get 
back when I access it? `nil`? `RecordNotFound` exception? If I have a 
validation that requires the presence of that missing object, does `save` still 
work?

There are plenty more questions like those. “Muddling through” with bad data is 
almost certainly going to break something upstream in people’s applications - 
something considerably harder to troubleshoot than a straightforward 
`SubclassNotFound` error on loading a bad record.

As to the “sample data” issue, if it’s worth keeping in the DB it’s worth 
keeping in source control. If writing a db/seeds.rb file is too complicated 
(maybe you’re importing large datasets from elsewhere), I’d recommend things 
like YamlDb to make repeatable seed data. Even `mysqldump  sample_data.sql` is 
a start…

—Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] Schema.rb table and column order

2015-01-19 Thread Matt Jones

On Jan 17, 2015, at 5:01 AM, vesan vesan2...@gmail.com wrote:

 When multiple people are working on a single Rails codebase and they add 
 migrations with new columns (or tables) and run the migrations in different 
 order there is a problem with schema.rb. After this every time migrations are 
 run the columns swap places if the previous version of the schema.rb file has 
 been commited by the other developer who did run the migrations in different 
 order.
 
 Because of this the developers have to discard the lines where columns swap 
 places to keep the source control clean. Could this be fixed by putting the 
 tables and columns on schema.rb in alphabetical order? Or are people relying 
 on the database's order of the tables and columns?
 
 It seems you could implement it by sticking `.sort_by(:name)` to 
 https://github.com/rails/rails/blob/3f96b6973b82ad17e443dd1d21be05996fb6fbf0/activerecord/lib/active_record/schema_dumper.rb#L134

There’s not a ton of evidence that column order can affect performance, but 
there are definitely cases - MyISAM tables with many varchar columns, for 
instance, will take longer to retrieve columns that are later in a row:

http://explainextended.com/2009/05/21/choosing-column-order/ (YMMV, I haven’t 
performed this experiment myself)

If this is added, it should be something users can switch off.

—Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] `to_key` return value

2015-01-19 Thread Matt Jones

On Jan 17, 2015, at 6:10 AM, Vipul A M vipulnsw...@gmail.com wrote:

 `to_key` was first introduced in 
 https://github.com/rails/rails/commit/9acd686753c43612984aaa4002e80113fda2b255
 
 As far as I can tell, we have never actually needed to wrap the primary key 
 in an array and don't have its use anywhere.
 
 Thoughts on changing this behaviour and just returning single primary field 
 instead?

The composite_primary_key user community probably have an opinion on this. 
They’d be stuck making workarounds to replace this:

https://github.com/composite-primary-keys/composite_primary_keys/blob/7a519429600715f7140f3dcda5efe18c73976996/lib/composite_primary_keys/base.rb#L126

—Matt Jones


-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] Proposal for before_transaction callback

2014-12-23 Thread Matt Jones
 from the beginning of this message has the same 
execution-timing problem, but is clearer IMHO because it’s not promising via 
naming things that it can’t actually deliver.

—Matt Jones


-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] Method to find inside of relation

2014-11-24 Thread Matt Jones

On Nov 22, 2014, at 5:03 PM, Sunny Juneja jr.su...@gmail.com wrote:

 Hey everyone,
 
 I've obviously done a bad job of explaining this :). Let me try to elaborate. 
 
 Suppose I've ran xyz = Model.where(attribute: true)
 A SQL query is created and executed. The results are saved to xyz as an 
 ActiveRecord_Relation. The query looks something like this:
 SELECT  models.* FROM models  WHERE models.attribute = ’t'

This is a place that people frequently get confused - doing this only runs the 
query in the REPL, where the result has `inspect` called on it for printing.

Try this in the REPL to see the difference:

xyz = Model.where(attribute: true); nil

This will set `xyz` but not trigger the query. Any subsequent code that 
attempts to access elements of `xyz` will trigger the query - so `to_a`, or 
`each`, etc.

Note that some methods will trigger a different query - for instance, calling 
`xyz.first` will perform a query with `LIMIT 1` if the records haven’t been 
loaded yet.

 If I run xyz.find_by(attribute2: false), a nw SQL query is created and 
 executed and it will hit the database again. The query looks something like 
 this:
 SELECT  models.* FROM models  WHERE models.attribute = 't' AND 
 models.attribute2 = 'f' LIMIT 1

 On the other hand, the proposed find_in_relation is a method on an 
 ActiveRecord_Relation that doesn't hit the database and searches the relation 
 in memory.
 
 If I type xyz.find_in_relation(attribute2: false), no new sql query is 
 created and it will not touch the database. The code would be equivalent to 
 running:
 xyz.select { |x| x.attribute2 == false }
 
 Ideally, find_in_relation would return another ActiveRecord_Relation.
 

`Relation` is intended to build queries. The results of in-memory filtering are 
not going to make that possible, in general, short of flattening everything to 
a giant `id IN (?)` clause.

The only use case I can see for something like this is when some of the 
attributes you’re filtering by aren’t DB columns but instead are model methods. 
For that case, `select` seems
to make the in-memory filtering aspect clearer.

—Matt Jones




-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] Method to find inside of relation

2014-11-16 Thread Matt Jones

On Nov 14, 2014, at 4:05 PM, Sunny Juneja jr.su...@gmail.com wrote:

 Hey, I ran into this problem fairly recently. I needed to get a large number 
 of records and search them over and over again on different attributes. I 
 found myself writing code that looked a lot like this.
 
 records = Model.where(...)
 
 records.select { |r| r.attribute1 == attribute1  r.attribute2 == attribute2 
  ... }
 
 Although this is a simple case, I found myself rewriting this over and over 
 again.
 
 Is there anything equivalent that might fit the form 
 
 records = Model.where(...)
 records.find_in_relation(attribute1: attribute1, attribute2: attribute2, 
 attribute3, ...)
 
 Was just wondering if there was a place for such syntactical sugar or a 
 desire to add some. If there is too simple a change to warrant, I understand.

If attribute1, attribute2, etc are database columns then I think `where` is the 
same as your `find_in_relation`…

records = Model.where(...)
records.where(attribute1: attribute1, attribute2: attribute2, attribute3, …)

Can you explain further what `find_in_relation` is intended to do differently?

—Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] Adding dirty checking by default to uniqueness validations

2014-11-07 Thread Matt Jones

On Nov 6, 2014, at 1:40 PM, Ryan Moser ryanpmo...@gmail.com wrote:

 I find it a bit odd that validates_uniqueness_of always hits the database 
 even when the attribute we are concerned with has not changed. It's easy 
 enough to add a dirty checking condition to a uniqueness validation, but it 
 seems like this should be the default behavior and always running the 
 validation should require some sort of a flag. Would this change be accepted?
 

You can get the behavior you want with an `if` option, I believe:

validates_uniqueness_of :foo, if: :foo_changed?

The behavior of all the *other* validations is “run every time the record is 
saved”, so I don’t think it would make sense for one of them to be different 
out-of-the-box.

—Matt Jones




signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] has_association? method on ActiveRecord

2014-11-06 Thread Matt Jones

On Nov 6, 2014, at 12:33 AM, Danny Sperry danny.spe...@gmail.com wrote:

 About a month ago I ran into a case where I needed to know if an AR object's 
 association exists dynamically. I was building a CMS Engine.
 
 I thought maybe this was a one off, but last week I found out my co-worker 
 also had a need for this in the CMS he was building. So I've come to the 
 community to see if this is something we think should be added into 
 ActiveRecord.
 
 I originally solved for this quite naively with the following solution
 
 def is_association?(attribute)
   respond_to?(attribute)  !attribute_names.include?(attribute.to_s)
 end
 
 and after trying to actually solve it in ActiveRecord I discovered 
 reflections. I think this is easily solved with something like the following 
 method inside lib/active_record/assocations.rb or 
 lib/active_record/relation.rb
 
 def has_association?(name)
   reflections.include? name
 end
 
 I'm new to contributing to open source and have been developing with Rails 
 for about a year so any and all questions, comments, criticism is welcome.
 
 Thanks!

I’m not certain where this would be useful, since every time I’ve needed to 
check for an association’s existence it was as a warmup to actually doing 
something with the reflection object.

As an example, this code:

if has_association?(:foobar)
  refl = reflect_on_association(:foobar)
  …

could just as well be written:

refl = reflect_on_association(:foobar)
if refl
  …

Can you discuss why has_association? would be useful in your code?

—Matt Jones




signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] Feature Request: form associated element

2014-10-14 Thread Matt Jones

On Oct 13, 2014, at 10:34 PM, Khoa Nguyen huu.khoa.ngu...@gmail.com wrote:

 As far as I know, Rails doesn't generate form attribute for input control 
 tags because it's assumed that form content is captured and rendered within a 
 block.
 
 # typical rails form usage
 %= form_for(object) do |f| %
   %= f.text_field :bam %
 % end %
 # generates
 form ...
   ...
   input name=object[bam] type=text
 /form
 
 
 The assumption has a limitation that content must not contain another form 
 element. [w3 
 spec](http://www.w3.org/TR/2011/WD-html5-20110525/association-of-controls-and-forms.html#association-of-controls-and-forms)
  defines a set of attributes on input tags to associate themselves to their 
 form.
 
  
 # decoupled control and its form
 form id=flexible...
 /form
 # control input can be placed outside of form tag
 # but still be associated to its form
 input form=flexible name=object[bam] type=text
 
 
 Will Rails support auto generation of form attribute on input controls, that 
 are outside of form tag? Is this feature on the roadmap?
 
 Quick hacks are most welcomed :)

Auto-generation seems unlikely - the ID of every form on the page would have to 
be stashed someplace template-wide and then the right one would need to be 
picked. That’s not even counting how *forward* references would need to work 
(form elements that precede the form in the DOM).

Haven’t tried it, but does explicitly adding `form: ‘whatever_your_form_id_is’` 
to the `html_options` for an input tag do the right thing?

—Matt Jones




signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] [Feature request] ActiveModel::Validations::NumericalityValidator multiple_of? integration

2014-09-17 Thread Matt Jones

On Sep 17, 2014, at 9:09 AM, Matteo Panara matteo.pan...@gmail.com wrote:

 Why not?
 
 module ActiveModel
   module Validations
 class NumericalityValidator  EachValidator
   CHECKS = { greater_than: :, greater_than_or_equal_to: :=,
 equal_to: :==, less_than: :, less_than_or_equal_to: :=,
 multiple_of: :multiple_of?, odd: :odd?, even: :even?,
 odd: :odd?, even: :even?, other_than: :!= }.freeze
 

multiple_of isn’t a supported option for NumericalityValidator because the 
method only exists for integers. Here’s some previous discussion of this 
situation:

https://github.com/rails/rails/pull/7216 (on why multiple_of isn’t defined for 
all of Numeric)

https://github.com/rails/rails/pull/7213 (on adding this exact feature)

TL;DR the core of the problem is that % is a tricky operator for floating-point 
numbers. 1.0 % 0.1, for instance, is usually NOT 0.0 like you’d expect…

—Matt Jones




signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] assign_attributes method not found

2014-09-03 Thread Matt Jones
assign_attributes went away in the move from 2.3 - 3.0, then re-appeared for 
3.1.0. In 3.0.5, the closest equivalent is plain `attributes=`.

Regarding security updates, the best versions to use security-wise are always 
(in descending order of preference):

* GREAT: the current release version (4.1.5 now, with 4.2 in beta)

* OKAY: the most-recent release of the previous version (4.0.9)

* KINDA NOT ENTIRELY BAD: the most-recent release of the any versions before 
*that* (3.2.19, 3.1.12, 3.0.20)

Older versions *only* get security updates, so the final releases in a 
particular line are almost always solving important security issues.

—Matt Jones

On Sep 3, 2014, at 10:12 AM, skt stibre...@gmail.com wrote:

 Thanks Ryan.
 
 I have a User model (using Devise/Omniauth) and I call the assign_attributes 
 on an instance of User.
 
 Part of what I am wondering is why isn't there a definition of 
 assign_attributes in the ActiveRecord::Base class in 3.0.5 that I am using.
 
 Thanks for any insights/pointers.
 
 -S
 
 On Tuesday, September 2, 2014 9:37:20 PM UTC-7, Ryan Bigg wrote:
 Hi skt,
 
 First of all: I would highly encourage you to upgrade immediately to at least 
 3.0.20.
 
 Second: What method are you calling exactly to get that error?
 
 
 On Wed, Sep 3, 2014 at 2:35 PM, skt stib...@gmail.com wrote:
 
 Hello,
 
 I am on an old version of Rails (3.0.5) and can't upgrade right now. When I 
 try to use assign_attributes on a model I get the error that the method is 
 not found as below
 
 NoMethodError - undefined method `assign_attributes' for 
 #User:0x007ffb7c2ae638:
   activemodel (3.0.5) lib/active_model/attribute_methods.rb:364:in 
 `method_missing'
   activerecord (3.0.5) lib/active_record/attribute_methods.rb:46:in 
 `method_missing'
 
 I searched for the method in the classes where update_attributes is defined 
 but indeed I couldn't find assign_attributes defined in any of the gems. From 
 the history of the method in the docs I understand it was created in 2.3.8 so 
 I would think the method would be there in 3.0.5.
 
 Any thoughts on why my ActiveRecord 3.0.5 gem doesn't have this method 
 defined?
 
 Thanks,
 -S
 
 -- 
 You received this message because you are subscribed to the Google Groups 
 Ruby on Rails: Core group.
 To unsubscribe from this group and stop receiving emails from it, send an 
 email to rubyonrails-co...@googlegroups.com.
 To post to this group, send email to rubyonra...@googlegroups.com.
 Visit this group at http://groups.google.com/group/rubyonrails-core.
 For more options, visit https://groups.google.com/d/optout.
 
 
 -- 
 You received this message because you are subscribed to the Google Groups 
 Ruby on Rails: Core group.
 To unsubscribe from this group and stop receiving emails from it, send an 
 email to rubyonrails-core+unsubscr...@googlegroups.com.
 To post to this group, send email to rubyonrails-core@googlegroups.com.
 Visit this group at http://groups.google.com/group/rubyonrails-core.
 For more options, visit https://groups.google.com/d/optout.



signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] Hash#extract missing from activesupport core extensions

2014-08-13 Thread Matt Jones

On Aug 13, 2014, at 11:18 AM, Peter Inglesby peter.ingle...@gmail.com wrote:

 Why does core_ext/hash/slice define Hash#slice, Hash#slice!, and 
 Hash#extract!, but not extract?  Would a patch be welcomed?

A non-destructive version of `extract!` would do exactly the same thing as 
`slice`: return a new Hash with only the given keys.

—Matt Jones



signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] strong parameters safety issue enables accidental mass assignment

2014-08-06 Thread Matt Jones

On Aug 6, 2014, at 12:51 PM, johannes.schlumber...@appfolio.com wrote:
[snip]
  
 Why does that matter?
 It matters because it is possible for a developer to accidentally lose that
 capability accidentally very easily on the way from the controller (where
 permit happened and the capability gets created) to the model (where the
 capability gets used). This loss does happen silently and effectively disables
 mass assignment protection.
 
 How does that happen?
 The only class aware of the 'permitted?' capability is
 ActiveController::Parameters, if we call a method that is not aware of the
 capability it can get lost as a side effect:
 
 class SomeModel  ActiveRecord::Base
   #fields :name, :protected_secret_field
   include ActiveModel::ForbiddenAttributesProtection
 end
 
 #imagine a request w/ params = {'name' = 1, 'protected_secret_field' = 2}:
 params.reject!{|k,_|['controller', 'action'].include? k}
 params.permit(:name)
 SomeModel.new(params) #Exception, world is OK
 SomeModel.new(params.symbolize_keys) #No Exception, secret overwritten
 

This is a bug in `symbolize_keys`. It appears to have been fixed (accidentally? 
on purpose?) on master:

https://github.com/rails/rails/commit/f1bad130d0c9bd77c94e43b696adca56c46a66aa

by starting the loop with `self.class.new` instead of `{}`.

There’s some additional future changes coming up in Ruby 2.2.0 with methods 
like `reject`:

https://www.ruby-lang.org/en/news/2014/03/10/regression-of-hash-reject-in-ruby-2-1-1/

that seem likely to further complicate the situation.

—Matt Jones



signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] Feature request: Modify TimeWithZone#as_json to take in an option to exclude decimal fractions

2014-06-26 Thread Matt Jones

On Jun 26, 2014, at 12:44 PM, Kirk Chen chen.k...@gmail.com wrote:

 Currently the TimeWithZone#as_json always returns 3 decimal points. However, 
 the ISO 8601 standard also supports no decimal point format.
 
 It would be great to add an option to the as_json method to not include 
 decimals. This would have several advantages.
 By default, it still returns 3 decimal points. This is the widely used (e.g. 
 by major browsers, Chrome, FF, Safari) option.
 It would support the no decimal point format part of the ISO 8601 standard.
 It allows Rails can communicate with APIs that is expecting no decimal 
 formats when needed.
This appears to be possible on an application-wide basis as of 4.1.0:

https://github.com/rails/rails/commit/c0965004486f2ea5a9656ba718a3377c9614f97d


—Matt Jones



signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] Feature Request: Do not allow to give Exception to rescue_from in controllers or at least show warning

2014-06-23 Thread Matt Jones

On Jun 23, 2014, at 9:48 AM, Yuki Nishijima m...@yukinishijima.net wrote:

 When building dynamic error pages, people (specially beginners) always write 
 rescue_from(Exception, ...) in ApplicationController. You can see it (or 
 something similar) is suggested on Stackoverflow and even RailsCasts.

The RailsCasts example is framed as “you really shouldn’t do this” with 
explanatory text as to *why* it’s a bad thing to do.

The StackOverflow example is explicitly attempting to construct a general 
exception notifier - a *replacement* for exception_notification and airbrake.

 However, doing so has serious side-effects such as listed below because it 
 halts the error chain:
 
   * No longer able to see nice exception details during development
   * gems like exception_notification and airbrake stops working
 
 In addition, I've never seen any good use-cases of it in controllers. So I 
 think it only gives us serious issues.
 
 And here's what I propose:
 
   * ActiveSupport::Rescuable remains the same
   * ActionController::Rescue overrides rescue_from and change it to not 
 accept Exception(raise some exception or output warning)

Rescuing `Exception` is not the best practice, but there are reasons that 
somebody might want to do it. We can’t save people from doing 
silly-but-potentially-valid things.

—Matt Jones



signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] Simplifying `rails new`

2014-06-12 Thread Matt Jones

On Jun 11, 2014, at 9:34 PM, Pier-Olivier Thibault poth...@gmail.com wrote:

 You are right. However, the initializers is not really what's discussed here. 
 it's the whole directory structure. Anyway, I think config/ folder still has 
 its place( and the initializers for all I care). I think the issue is that 
 over the years, the project structure for Rails has grown to have a lot of 
 different folder and the meaning of all those folders is not that obvious. 
 Initializers were never a part of the discussion anyway until you mentionned 
 it.
 

The post I originally replied to (from Joe Fiorini) mentioned the config folder 
potentially being unnecessary. That would tend to involve initializers. :)

—Matt Jones

 On Wednesday, June 11, 2014 6:42:52 PM UTC-4, Matt jones wrote:
 
 On Jun 11, 2014, at 3:13 PM, Pier-Olivier Thibault pot...@gmail.com wrote:
 
 On Wednesday, June 11, 2014 3:57:59 PM UTC-4, Matt jones wrote:
 
 On Jun 11, 2014, at 12:32 PM, Joe Fiorini j...@joefiorini.com wrote:
 
 I actually played with simplifying the structure some time ago, although 
 for a completely different use case. I didn't end up going further than 
 posting this PoC on Github, but it does actually boot up a Rails app.
 
 My changes:
 
 I moved all application/environment config into a file called 
 {APP_NAME}.rb. Inside this file I have a module/class definition for the 
 application the same as any standard Rails app (looks like I accidentally 
 made it a class rather than Application class inside APP_NAME module, 
 oops), but I also added a Ruby DSL for specifying environment configs. IME, 
 the files under config/environments don't normally get a ton of options, so 
 having them all in one place would actually be easier.
 
 
 Would this mean smashing all the files in config/initializers into one file? 
 That would make generators that wanted to create a default initializer (for 
 instance, the Devise InstallGenerator) much more complicated since they’d 
 need to insert code into the singular environment.rb file rather than just 
 drop a whole file into config/initializers.
 
 I believe it would be the opposite, people, instead of using the 
 config/initializers/*.rb, they would use mechanics that Rails provides by 
 default - The initializer method that any railtie class have. Here's an 
 example of an application.rb file that would include such 
 initializer:https://gist.github.com/pothibo/a32f686aed0f03729157 
 
 In your example, the generator would have to *insert* an additional 
 `initializer ‘whatever’ do` block into the existing generator. That’s already 
 going to make things more complicated; finding the appropriate place is not 
 trivial, especially if the generator needs to play nice with namespaced 
 applications, such as:
 
 module MyTopLevel
   module MyProject
 class Application  Rails::Application
 
   initializer 'configure devise' do |app|
 app.config.devise.somethin = 'blabla'
   end
 end
   end
 end
 
 A simplistic strategy (“insert before the 2nd end from the end of the file”) 
 will fall down here.
 
 More importantly, the *size* of what’s added is significant. The Devise 
 generator alone drops 260+ lines (mostly comments) to help users configure 
 things. 
 
 The application.rb file seems like it could get quite long, and then somebody 
 will propose to split it up into, say, a directory of smaller files… :)
 
 —Matt Jones
 
 
 I also haven’t seen much discussion of the “set up the paths but don’t load 
 the whole env” reasoning for boot.rb being separate from environment.rb 
 (mentioned down-thread by Ryan Bigg). Is this still something useful? If it 
 isn’t, how will (for instance) Rake tasks that don’t depend on :environment 
 be switched over?
 
 —Matt JOnes
 
 
 
 I also removed the app folder and put directories that were in that 
 folder in the root. This change was specific to the particular use case I 
 was designing this for, API-only apps that don't have as much need for the 
 app distinction.
 
 Once I started thinking about a smaller Rails structure, the idea of the 
 config folder seemed unnecessary. Anytime I need access to my app's 
 environment I require application.rb, so to me the distinction between 
 that and environment.rb doesn't serve much purpose. Given that, why can't 
 boot.rb be in the root and all the environment config be consumed into 
 application.rb with a DSL for creating environments like above?
 
 On Tuesday, June 10, 2014 6:50:48 PM UTC-4, Pier-Olivier Thibault wrote:
 How would you execute the rails binary without using `bundle exec` within 
 an application? Wouldn't that defeat the purpose of binstubs? Rails isn’t 
 installed on anything but our development machines outside of bundler.
 
 I think this is somewhat open to discussion. What is the difference between 
 'bundle exec rails server' and './bin/rails server' besides the longer 
 command, of course?
 
 I would personally pay the cost of longer commands to see

Re: [Rails-core] Simplifying `rails new`

2014-06-11 Thread Matt Jones

On Jun 11, 2014, at 12:32 PM, Joe Fiorini j...@joefiorini.com wrote:

 I actually played with simplifying the structure some time ago, although for 
 a completely different use case. I didn't end up going further than posting 
 this PoC on Github, but it does actually boot up a Rails app.
 
 My changes:
 
 I moved all application/environment config into a file called 
 {APP_NAME}.rb. Inside this file I have a module/class definition for the 
 application the same as any standard Rails app (looks like I accidentally 
 made it a class rather than Application class inside APP_NAME module, oops), 
 but I also added a Ruby DSL for specifying environment configs. IME, the 
 files under config/environments don't normally get a ton of options, so 
 having them all in one place would actually be easier.
 

Would this mean smashing all the files in config/initializers into one file? 
That would make generators that wanted to create a default initializer (for 
instance, the Devise InstallGenerator) much more complicated since they’d need 
to insert code into the singular environment.rb file rather than just drop a 
whole file into config/initializers.

I also haven’t seen much discussion of the “set up the paths but don’t load the 
whole env” reasoning for boot.rb being separate from environment.rb (mentioned 
down-thread by Ryan Bigg). Is this still something useful? If it isn’t, how 
will (for instance) Rake tasks that don’t depend on :environment be switched 
over?

—Matt JOnes



 I also removed the app folder and put directories that were in that folder 
 in the root. This change was specific to the particular use case I was 
 designing this for, API-only apps that don't have as much need for the app 
 distinction.
 
 Once I started thinking about a smaller Rails structure, the idea of the 
 config folder seemed unnecessary. Anytime I need access to my app's 
 environment I require application.rb, so to me the distinction between that 
 and environment.rb doesn't serve much purpose. Given that, why can't 
 boot.rb be in the root and all the environment config be consumed into 
 application.rb with a DSL for creating environments like above?
 
 On Tuesday, June 10, 2014 6:50:48 PM UTC-4, Pier-Olivier Thibault wrote:
 How would you execute the rails binary without using `bundle exec` within an 
 application? Wouldn't that defeat the purpose of binstubs? Rails isn’t 
 installed on anything but our development machines outside of bundler.
 
 I think this is somewhat open to discussion. What is the difference between 
 'bundle exec rails server' and './bin/rails server' besides the longer 
 command, of course?
 
 I would personally pay the cost of longer commands to see lighter project 
 file structure as I'm going to spend much more time in the project than I 
 will executing commands. It's important to note that rake tasks are going to 
 stay as is.
 
 -- 
 You received this message because you are subscribed to the Google Groups 
 Ruby on Rails: Core group.
 To unsubscribe from this group and stop receiving emails from it, send an 
 email to rubyonrails-core+unsubscr...@googlegroups.com.
 To post to this group, send email to rubyonrails-core@googlegroups.com.
 Visit this group at http://groups.google.com/group/rubyonrails-core.
 For more options, visit https://groups.google.com/d/optout.



signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] Simplifying `rails new`

2014-06-11 Thread Matt Jones

On Jun 11, 2014, at 3:13 PM, Pier-Olivier Thibault poth...@gmail.com wrote:

 On Wednesday, June 11, 2014 3:57:59 PM UTC-4, Matt jones wrote:
 
 On Jun 11, 2014, at 12:32 PM, Joe Fiorini j...@joefiorini.com wrote:
 
 I actually played with simplifying the structure some time ago, although for 
 a completely different use case. I didn't end up going further than posting 
 this PoC on Github, but it does actually boot up a Rails app.
 
 My changes:
 
 I moved all application/environment config into a file called 
 {APP_NAME}.rb. Inside this file I have a module/class definition for the 
 application the same as any standard Rails app (looks like I accidentally 
 made it a class rather than Application class inside APP_NAME module, oops), 
 but I also added a Ruby DSL for specifying environment configs. IME, the 
 files under config/environments don't normally get a ton of options, so 
 having them all in one place would actually be easier.
 
 
 Would this mean smashing all the files in config/initializers into one file? 
 That would make generators that wanted to create a default initializer (for 
 instance, the Devise InstallGenerator) much more complicated since they’d 
 need to insert code into the singular environment.rb file rather than just 
 drop a whole file into config/initializers.
 
 I believe it would be the opposite, people, instead of using the 
 config/initializers/*.rb, they would use mechanics that Rails provides by 
 default - The initializer method that any railtie class have. Here's an 
 example of an application.rb file that would include such 
 initializer:https://gist.github.com/pothibo/a32f686aed0f03729157 

In your example, the generator would have to *insert* an additional 
`initializer ‘whatever’ do` block into the existing generator. That’s already 
going to make things more complicated; finding the appropriate place is not 
trivial, especially if the generator needs to play nice with namespaced 
applications, such as:

module MyTopLevel
  module MyProject
class Application  Rails::Application

  initializer 'configure devise' do |app|
app.config.devise.somethin = 'blabla'
  end
end
  end
end

A simplistic strategy (“insert before the 2nd end from the end of the file”) 
will fall down here.

More importantly, the *size* of what’s added is significant. The Devise 
generator alone drops 260+ lines (mostly comments) to help users configure 
things. 

The application.rb file seems like it could get quite long, and then somebody 
will propose to split it up into, say, a directory of smaller files… :)

—Matt Jones

 
 I also haven’t seen much discussion of the “set up the paths but don’t load 
 the whole env” reasoning for boot.rb being separate from environment.rb 
 (mentioned down-thread by Ryan Bigg). Is this still something useful? If it 
 isn’t, how will (for instance) Rake tasks that don’t depend on :environment 
 be switched over?
 
 —Matt JOnes
 
 
 
 I also removed the app folder and put directories that were in that folder 
 in the root. This change was specific to the particular use case I was 
 designing this for, API-only apps that don't have as much need for the app 
 distinction.
 
 Once I started thinking about a smaller Rails structure, the idea of the 
 config folder seemed unnecessary. Anytime I need access to my app's 
 environment I require application.rb, so to me the distinction between 
 that and environment.rb doesn't serve much purpose. Given that, why can't 
 boot.rb be in the root and all the environment config be consumed into 
 application.rb with a DSL for creating environments like above?
 
 On Tuesday, June 10, 2014 6:50:48 PM UTC-4, Pier-Olivier Thibault wrote:
 How would you execute the rails binary without using `bundle exec` within an 
 application? Wouldn't that defeat the purpose of binstubs? Rails isn’t 
 installed on anything but our development machines outside of bundler.
 
 I think this is somewhat open to discussion. What is the difference between 
 'bundle exec rails server' and './bin/rails server' besides the longer 
 command, of course?
 
 I would personally pay the cost of longer commands to see lighter project 
 file structure as I'm going to spend much more time in the project than I 
 will executing commands. It's important to note that rake tasks are going to 
 stay as is.
 
 -- 
 You received this message because you are subscribed to the Google Groups 
 Ruby on Rails: Core group.
 To unsubscribe from this group and stop receiving emails from it, send an 
 email to rubyonrails-co...@googlegroups.com.
 To post to this group, send email to rubyonra...@googlegroups.com.
 Visit this group at http://groups.google.com/group/rubyonrails-core.
 For more options, visit https://groups.google.com/d/optout.
 
 
 -- 
 You received this message because you are subscribed to the Google Groups 
 Ruby on Rails: Core group.
 To unsubscribe from this group and stop receiving emails from it, send an 
 email to rubyonrails

Re: [Rails-core] HttpOnly cookies by default

2014-05-18 Thread Matt Jones
I’ve had to resort to some pretty weird cookie stuff when passing data between 
a Rails app and non-Rails applications. The session is handy, but parsing it 
anywhere but in Rails is difficult and *updating* it outside of Rails is more 
difficult.

—Matt Jones

On May 17, 2014, at 9:12 AM, Gabriel Sobrinho gabriel.sobri...@gmail.com 
wrote:

 I would argue that if you have some information that can't be hijacked and 
 even parsed on javascript (httponly cookies can't be read on javascript at 
 all), why would you use cookies instead of the rails session?
 
 On Friday, May 16, 2014 7:07:42 PM UTC-3, fedesoria wrote:
 I would like to see this happen, since when dealing with Enterprise 
 Vulnerability Scans it always comes up.
 
 On Monday, January 7, 2013 2:09:42 PM UTC-8, Stephen Touset wrote:
 Earlier, someone proposed on the GH issues tracker that Rails default all 
 cookies to HttpOnly[1]. Rails already makes the session cookie HttpOnly, but 
 given a general to keep Rails secure-by-default, it would probably be best if 
 *all* cookies defaulted to HttpOnly. This would be a compatibility-breaking 
 change, but it wouldn't be difficult to add a configuration option that can 
 be defaulted to false for existing Rails apps that are upgraded.
 
 I'm more than happy to write the code for this change, but wanted to discuss 
 it here first to see if anyone objects strongly. Josh Peek had concerns with 
 backwards compatibility, but I think my proposal above for a configuration 
 option should satisfy them. Anyone care to weigh in?
 
 [1] https://github.com/rails/rails/issues/1449
 
 -- 
 You received this message because you are subscribed to the Google Groups 
 Ruby on Rails: Core group.
 To unsubscribe from this group and stop receiving emails from it, send an 
 email to rubyonrails-core+unsubscr...@googlegroups.com.
 To post to this group, send email to rubyonrails-core@googlegroups.com.
 Visit this group at http://groups.google.com/group/rubyonrails-core.
 For more options, visit https://groups.google.com/d/optout.



signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] smart eager loading and caching

2014-05-18 Thread Matt Jones

On May 16, 2014, at 2:35 PM, Lawrence Wu lawre...@lawrencewu.me wrote:

 I'd like to deprecate methods like includes and eager_load in Rails since I 
 think it is possible to automatically detect when they are needed. Ideally 
 the developer could know very little about how databases work and still get 
 very efficient queries using just the ORM. What do other people think?

I’m not terribly convinced that there’s a useful heuristic to automatically 
make the right choices for eager-loading, since the right associations to load 
are typically driven by what the code does with the results.

For instance, this code fragment should either use something different than 
`present?` or should use an eager-load, but the right choice depends on what 
happens after the records are loaded:

@posts.each do |post|
  # present? will cause the comments association to load
  if post.comments.present?
# do something
# if post.comments is referenced here, it should have been eager-loaded
# if it isn’t referenced, the present? should really be changed to exists? 
or similar
  end
end

Even if such a heuristic existed, it would still be wrong some of the time - so 
things like `includes` and `eager_load` would still be needed to specify the 
correct behavior in those cases.

It’s definitely worth discussing, but it’s going to (IMO) face a pretty steep 
climb to success. 

—Matt Jones


signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] Named has_*

2014-05-01 Thread Matt Jones

On May 1, 2014, at 11:57 AM, Łukasz Niemier luk...@niemier.pl wrote:

 It will be nice, if has_* methods will have named option. Example:
 
 has_many :foos, named: :boos
 
 # equivalent of
 
 has_many :boos, class_name: 'Foo', foreign_key: 'foo_id'
 
 IMHO it is quite often used feature. Also it will be nice to have scoped 
 option that will allow easy flow with scoped models (i.e. Blog::Posts).

-1 on this. The first argument of `has_many` is the name you want to refer to 
the association by (the root name of all the generated methods), not the 
pluralized model name.

It’s sufficiently confusing that I’m pretty sure your expanded example is 
incorrect; `Foo` is unlikely to have a column named `foo_id`…

—Matt Jones


signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] Improvements to Strong Params

2014-05-01 Thread Matt Jones

On Apr 30, 2014, at 10:00 PM, Alexander Trauzzi atrau...@gmail.com wrote:

 I've just been getting re-acquainted with Rails 4 after spending the past 
 year working in some other frameworks.
 
 One thing I noticed are strong parameters which I see as a really great 
 addition!  One flaw I've noticed however is in the behaviour of 
 `params.require` which I don't think is 100% user friendly yet.  The two 
 major issues I can see are:
 
  - It returns a value, when really what it should be doing is returning 
 params to continue with a fluent API
  - It doesn't accept multiple values (an array)
 
 It's been observed in the strong params github issue tracker by several 
 others that this violates the principle of least astonishment by coupling 
 unrelated functionality (returning nested keys) with the enforcement of 
 parameter presence.  It also could be argued that people might expect to be 
 able to use it as follows:
 
 my_params = params.require(:one, :two, :three).permit(:one, :two, :three, 
 :four)
 

What would this specify the expected format *as*? Doing the more usual:

params.require(:one).permit(:one, :two, :three, :four)

is saying that you expect params like:

  one:
one: (scalar)
two: (scalar)
three: (scalar)
four: (scalar)

In the case where `require` takes multiple keys, is it expecting the sub keys 
in *each* of those? Any of them?


 This basically sets up a simple request-specific schema for parameter 
 presence as it begins to travel further into the application's layers.  I 
 think the feature of params.require being able to verify the presence of a 
 key and then returning it's contents for nested attributes needlessly couples 
 two pieces of functionality.  I typically store all attributes for a request 
 at the root of my `params` and so I never have any nested object data to 
 dereference.  It's all at the top, and this results in me having to make 
 multiple separate calls to `params.require` just to verify each one.  Which 
 as I'm sure you can guess gets very ugly, very quickly:
 
 params.require :one
 params.require :two
 params.require :three
 my_params = params.permit :one, :two, :three, :four

Does this actually work? I swear I’ve gotten into trouble with calling `permit` 
on the top-level params hash, since there’s other stuff (:controller, :action, 
:format, etc) in there…

—Matt Jones



signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] delete_all with limit

2014-04-03 Thread Matt Jones

On Apr 3, 2014, at 2:28 PM, Isha i...@jadedpixel.com wrote:

 Hi,
 
 I was wondering if there is a specific reason why delete_all does not accept 
 limits? Ultimately, I want to achieve batched deletes in my application and 
 something like delete_in_batches or even delete_allthat accepts limits would 
 be useful.
 
 I can try adding this but wanted to get some feedback/suggestions first.

FWIW, passing a LIMIT clause to a DELETE is included in the SQL92 standard, but 
actually-implemented support is spotty:

* Postgres: not supported
* Oracle: not supported (but maybe hackable with ROWNUM tricks)
* SQLite3: supported if enabled at compile time
* MySQL: supported
* SQL Server: not supported (but maybe with a TOP subquery?)

—Matt Jones


signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: [Rails-core] update_attribute violates POLA

2014-03-12 Thread Matt Jones

On Mar 12, 2014, at 7:23 AM, Anh Nguyen khac...@gmail.com wrote:

 POLA http://en.wikipedia.org/wiki/Principle_of_least_astonishment
 
 Examples
 
 ```
 # user.rb
 class User  ActiveRecord::Base
   attr_accessible :name, :username
   validates :username, uniqueness: true
 end
 
 user1 = User.create(name: 'Name 1', username: 'username1')
 user2 = User.create(name: 'Name 2', username: 'username2')
 
 user1.username = 'username2'
 user1.save # = false
 user1.update_attribute(name: 'New Name')
 user1.reload
 
 user1.username # = 'username2'
 # update_attribute is expected to update the specified attribute, not other 
 ones. Thus it is violating POLA
 ```

This behavior was exactly why update_attribute was (briefly) deprecated in 
3.2.7:

https://groups.google.com/forum/?hl=enfromgroups#!topic/rubyonrails-core/BWPUTK7WvYA

Not sure how it got un-deprecated...

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.


[Rails-core] Request for review - #14154

2014-03-03 Thread Matt Jones
I know it's late in the 4.1.0 release cycle, but I was hoping somebody could 
review this for that release:

https://github.com/rails/rails/pull/14154

It fixes an issue where default_scopes in ON clauses don't pick up the table's 
aliased name. Without the patch, the resulting queries are generally valid SQL 
but return incorrect results.

I'd also appreciate any insight people can put on #14155, but that's lower 
priority since it's been broken in the same fashion since 3.x.

Thanks,

--Matt Jones



-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/groups/opt_out.


Re: [Rails-core] Convention over configuration and the Rails.root-tmp-folder

2014-02-11 Thread Matt Jones

On Feb 11, 2014, at 3:11 PM, Thomas V. Worm t...@s4r.de wrote:

 ;-)
 
 I understand convention over configuration not the same as you do: you do not 
 need to configure if your are fine with the convention, but you can, if you 
 want or must. Like in ActiveRecord, when the table names can be derived from 
 the class names but can also be declared, when you have a legacy db.
 

The configuration is one level higher, when you pick a cache_store:

config.cache_store = :file_store, /path/to/cache/directory

(from the caching guide)

--Matt Jones

 Am Dienstag, 11. Februar 2014 19:52:15 UTC+1 schrieb Andrew Kaspick:
 You're contradicting yourself.  The /tmp folder is 100% convention and 0% 
 configuration.  Therefore it's all convention over configuration. :)
 
 
 
 On Tue, Feb 11, 2014 at 1:11 PM, Thomas V. Worm t...@s4r.de wrote:
 Hi,
 
 I started to write a tiny rails app which comes completely as a ruby gem. 
 Since this app has a big cousin in rails I did not want to use another 
 framework like sinatra.
 
 Since the app is a gem, I do not want it to store runtime-files in the 
 tmp-folder. So I thought I should not stay with the convention but configure 
 the location of the tmp-folder. But as far as I can see, there is no way to 
 configure it.
 
 I searched the source code and found lines like this one:
 
 ./railties/lib/rails/application/configuration.rb:@cache_store
= [ :file_store, #{root}/tmp/cache/ ]
 
 As one can see, the tmp-folder does not follow convention over configuration 
 but is hard coded.
 
 So what about adding a configuration option? I am using Rails 4.1.
 
 Regards
 Thomas
 
 -- 
 You received this message because you are subscribed to the Google Groups 
 Ruby on Rails: Core group.
 To unsubscribe from this group and stop receiving emails from it, send an 
 email to rubyonrails-co...@googlegroups.com.
 To post to this group, send email to rubyonra...@googlegroups.com.
 Visit this group at http://groups.google.com/group/rubyonrails-core.
 For more options, visit https://groups.google.com/groups/opt_out.
 
 
 -- 
 You received this message because you are subscribed to the Google Groups 
 Ruby on Rails: Core group.
 To unsubscribe from this group and stop receiving emails from it, send an 
 email to rubyonrails-core+unsubscr...@googlegroups.com.
 To post to this group, send email to rubyonrails-core@googlegroups.com.
 Visit this group at http://groups.google.com/group/rubyonrails-core.
 For more options, visit https://groups.google.com/groups/opt_out.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/groups/opt_out.


Re: [Rails-core] Engine dependency - rails or railties ?

2014-01-07 Thread Matt Jones

On Jan 7, 2014, at 5:52 AM, Emil S emil.so...@gmail.com wrote:

 Apologies if the question is too naive.
 
 When I create a new engine using `rails plugin new engine_name`, I can see 
 a default dependency on rails in gemspec. Engines such as devise only have 
 dependency on railties and not the whole of rails.
 
 Why is the default dependency rails and not railties” ?


My wild guess would be that a dependency on ‘rails’ will wind up depending on 
the whole set of framework gems (Active Record / Action Pack / etc) via the 
‘rails’ gemspec whereas the ‘railties’ dependency is limited only to the actual 
engine infrastructure.

In Devise’s case ‘railties’ is likely chosen since you can use different ORMs 
and skip the generated controllers if you really want to. For a generated 
engine, you really need the whole ‘rails’ gem, since it puts a full Rails app 
in the test/dummy directory.

—Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/groups/opt_out.


Re: [Rails-core] Idea for handling dirty active_record serialized columns

2014-01-06 Thread Matt Jones

On Jan 5, 2014, at 11:46 PM, Keenan Brock kee...@thebrocks.net wrote:

 Hello All,
 
 Currently, `serialized` columns get save to the database whether they are 
 changed or not. [Github][1]. Since the serialized columns can be modified 
 inline, `Dirty` is not used. This behavior introduces too much database 
 overhead for us, so I'd like to patch that code right out of there.
 
 ## Having trouble extending ActiveRecord
 
 `ActiveRecord::Base.ancestors` returns `ActiveRecord::Core` before 
 `ActiveRecord::AttributeMethods::Dirty`, so the methods in `Core` take 
 precedence over those in `Dirty`.
 
 I was thinking `Dirty` overrides the behavior of `Core` and should have 
 higher precedence. This would allow `@changed_attribtues` to move from `Core` 
 to `Dirty`.
 
 Is there history to this decision? Or is it even possible to change this? (I 
 mean from both technically, as well as logistically changing something so 
 core to the code.)
 
 ## Changing the way `Dirty` is implemented.
 
 I played around with storing the original values for an attribute, rather 
 than just the values that have been changed. [Github][2] Only cloning/storing 
 `@original_values` on attribute access keeps the code as close to the current 
 `@changed_attributes` implementation. It not only works with serialized 
 variables, but code like `model.field.gsub!('a','b')`, without requiring 
 `field_will_change!`

Cloning fails in exciting and (likely) unexpected ways when the serialized 
value is deeper than one level:

irb: hash = { a: [1,2,3], b: [4,5,6] }
=== {:a=[1, 2, 3], :b=[4, 5, 6]}
irb: hash2 = hash.clone
=== {:a=[1, 2, 3], :b=[4, 5, 6]}
irb: hash2[:a]  'baz'
=== [1, 2, 3, baz]
irb: hash
=== {:a=[1, 2, 3, baz], :b=[4, 5, 6]}

The only way I’ve found to reliably deep-clone objects is to chain together 
Marshal.dump and Marshal.load, but that’s almost *got* to be terrible for 
performance.

—Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/groups/opt_out.


Re: [Rails-core] Delegate default value option

2013-12-16 Thread Matt Jones

On Dec 13, 2013, at 5:44 PM, Scott Johnson wrote:

 I find I often use delegate and many nil guards in my facades.  Adding a 
 default_value option to delegate would simplify this, but I am interested how 
 others feel about it.
 
 Implementation would look something like:
 
 class PersonFacade 
   delegate :name, :to = :person, :default_value = 
   

It's not clear (to me) how this should interact with passing multiple 
attributes to `delegate`:

delegate :foo, :bar, :baz, :to = :person

Also, should the default value be returned if :allow_nil is set and the 
delegated-to object isn't present?

 --Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/groups/opt_out.


Re: [Rails-core] validates :boolean_field, presence: true misconceptions

2013-11-14 Thread Matt Jones

On Nov 14, 2013, at 8:14 AM, Sergio Campamá wrote:

 Last night a friend of mine started ranting about validates_presence_of 
 :boolean_field returning not valid when the boolean field is false. 
 
 I checked the rails issues and this seems to be a pretty common concern about 
 the naming of  'presence' .
 
 Instead of changing the behaviour of the presence validator, I was wondering 
 if maybe the answer to avoid such misconceptions could be to create a new 
 validator called presence_of_boolean that abstracts the sometimes called 
 hacky validates_inclusion in: [true, false]
 
 What do you guys think?

I think that if you're putting boolean columns in your DB that don't default to 
either true or false you are doing it wrong. If you really want yes / no / 
didn't answer semantics, use a type that represents that.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/groups/opt_out.


[Rails-core] Threading weirdness in method_missing

2013-10-23 Thread Matt Jones
Can somebody take a look at the discussion here:

https://github.com/rails/rails/pull/12607

(suggested fix at the bottom)

tl;dr: there's an obscure race condition which only happens when two threads 
dispatch into method_missing on instances of the same ActiveRecord model. The 
net result is that one of them successfully generates + calls the requested 
method while the other fails with NoMethodError. :(

The fix is (as far as I can tell) pretty straightforward, so this would be 
great to get into 4.0.1.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/groups/opt_out.


Re: [Rails-core] Response to “Logout is broken by default in Ruby on Rails web applications”?

2013-10-14 Thread Matt Jones

On Oct 14, 2013, at 11:28 AM, Steve Klabnik wrote:

 (I believe) it already is: 
 http://guides.rubyonrails.org/security.html#session-fixation

The new article is about a different scenario - namely that the CookieStore 
doesn't include any kind of invalidation mechanism by default.

Short version:

1: attacker steals a session cookie from user Victim (NOTE: user is already 
pwned at this point)

2: Victim logs out of the site

3: attacker uses the stolen cookie to continue acting as Victim

TBH, it's a bug to be sure - but calling it broken by default when the repro 
starts with Step 1: the user is utterly pwned seems a bit hyperbolic. 

Drink your SSL + Secure cookies, kids!

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/groups/opt_out.


Re: [Rails-core] Master-slave replication support

2013-10-11 Thread Matt Jones

On Oct 11, 2013, at 11:03 AM, Rafael Fernández López wrote:

   I find it great the idea of creating an external gem and integrate it 
 to the core later on. I understand that not everything can go inside the 
 core, but multiple database support (master-slaves) looks like something 
 really important the core could have without installing external gems.
 
   I have been reading on this matter, and octopus looks nice, but what I 
 actually want to avoid is this kind of API:
 
   User.where(:name = Thiago).limit(3).using(:slave_one)
 
   I'd love to map internally to one or another database (master or any 
 read-only replication) depending _on what the query will be_. This way you 
 don't have to mess with this kind of calls and everything happens in a 
 transparent way. So, the final sql query involves read only queries, then we 
 can safely access any of the replicas, however, if it involves any creation, 
 deletion or modification, it will connect to the master one.


That's pretty much exactly what replication in octupus does:

https://github.com/tchandy/octopus/wiki/replication

:)

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/groups/opt_out.


Re: [Rails-core] Inconsistent(?) datetime and timestamp handling

2013-09-18 Thread Matt Jones

On Sep 17, 2013, at 6:57 PM, Robb Shecter wrote:

 Matt jones wrote:
 
 The best type to use to store DateTime objects is database-dependent: 
 
 
 So Ketan's finding seems to be correct, and this is something we should fix. 
 I.e., Rails' concept of timestamps should be database independent, just as 
 its concept of the primary key type is. (?) 
 

I think you missed the point of my post: the choice of column MUST be 
database-dependent, since there's no type that's consistently available across 
all DB engines. 

Handling these differences in a way that's transparent to higher levels is one 
of ActiveRecord's responsibilities - for another example, note that boolean 
columns are stored in database-dependent ways: Mysql uses tinyint, SQLite uses 
a string with 't' or 'f', Postgres uses a native boolean type, etc.

For what it's worth, not even the primary key type is consistent if you go a 
little farther afield. For instance, the built-in Mysql adapter uses an 
INTEGER(11) field for primary keys, but the oracle-enhanced adapter uses 
NUMBER(38) which doesn't even have the same available range.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/groups/opt_out.


Re: [Rails-core] Inconsistent(?) datetime and timestamp handling

2013-09-12 Thread Matt Jones

On Sep 11, 2013, at 10:33 PM, Ketan Padegaonkar wrote:

 Hi,
 
 I noticed that datetimes and timestamps are handled inconsistently between 
 databases. Mysql treats them as datetime[1]. Postgres treats them as 
 timestamp[2]. Sqlite treats them as datetime[3].
 
 I read through the documentation around specifics of datetime and timestamps 
 in various databases and was wondering if there's a database specific nuance 
 that I do not understand or something else I'm missing. Could someone throw 
 some light at this?
 

The best type to use to store DateTime objects is database-dependent:

- in Mysql, there are both TIMESTAMP and DATETIME column types, but TIMESTAMP 
is limited to the 32-bit UNIX epoch (1970-01-01 to 2038-01-19) while DATETIME 
accepts values between 1000-01-01 and -12-31.

- in Postgres, there is only TIMESTAMP, which accepts values between 
-4713-01-01 and 294276-01-01 (or so...)

- SQLite doesn't exactly support a native DATETIME type, but it stores the 
values as strings. DATETIME is preferred (best I can tell) over TIMESTAMP 
because the SQLite gem parses TIMESTAMP columns into Time objects while 
DATETIMEs become DateTime objects.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/groups/opt_out.


Re: [Rails-core] Feature Request: Track habtm changes

2013-08-22 Thread Matt Jones

On Aug 22, 2013, at 11:56 AM, Gabriel Sobrinho wrote:

 Hey guys,
 
 What do you think about tracking habtm changes?
 
 Apparently we can't do that because when you change a habtm association it is 
 changed immediately on database instead of waiting the save call (not sure 
 why and the problem may not be because of that).
 
 Current behaviour:
 
 profile.roles_ids
 = []
 
 profile.update_attributes(:name = nil, :roles_ids = [...])
 = false
 
 profile.changes
 { name = ['Admin', nil] }
 
 
 Expected behaviour:
 
 profile.roles_ids
 = []
 
 profile.update_attributes(:name = nil, :roles_ids = [...])
 = false
 
 profile.changes
 { name = ['Admin', nil], :roles_ids = [[], [...]] }
 
 
 
 Giving some problem context, I have an application that need to audit almost 
 every change and I can track everything using the changes method but habtm 
 changes.
 
 We can write a solution like storing the initial state of roles_ids in an 
 after_initialize callback on the model and comparing it on a after_save but I 
 was thinking in a more native solution.
 
 
 What do you think?

Some quick thoughts:

* using the _ids= method on has_many doesn't show up in changes either

* this could get really expensive if you have a lot of rows on the other end of 
the HABTM, since you cache the complete list of IDs in memory

--Matt Jones


-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/groups/opt_out.


Re: [Rails-core] Creating Proxy-containers with ActiveSupport's delegate, proposing return_value_of keyword argument

2013-08-13 Thread Matt Jones

On Aug 12, 2013, at 7:25 PM, Amiel Martin wrote:

 I like this idea and I would use it.
 
 My only suggestion would be to normally return a new instance of the proxy 
 object. This makes it easier to use this feature with immutable objects.
 I know it would be possible to do this:
 
 class ProxyContainer  Struct.new(:brands)
   delegate :select, to: :brands, return_value_of: 'self.class.new(result)'
   # ...
 end
 
 but it's not obvious that you could do this without reading through the 
 definition.

We already have a DSL for specifying the return value of a method: it's called 
RUBY. :)

Snark aside, I think adding too many bells-and-whistles to `delegate` is not 
the best idea. If you really want custom behavior, why not make it clearer and 
just write the methods?

At a minimum, code-as-string is kinda gross. 

--Matt Jones




-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/groups/opt_out.


Re: [Rails-core] Re: false.present? is false. Is it desired behaviour?

2013-06-25 Thread Matt Jones

On Jun 25, 2013, at 7:36 AM, James Pinto wrote:

 I understand where you're coming from,
 and I completely disagree
 
 false is blank, but it's not nil,
 however, in some cases, falseness should not be validated
 
 validates_presence_of :aggrees_with_contract is correct, requires the user 
 to check the contract
 validates_presence_of :displays_photo_for_guests is incorrect, because it's 
 only a question and it's ok if the user forgets or chooses not to mark

If it's OK if the user doesn't send this value, *why* are you validating for it 
to be present? Set a default for your boolean column (which you should be doing 
anyways :) ) and have a nice life.

--Matt Jones


-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/groups/opt_out.




Re: [Rails-core] Casting gem usage in Rails 4/Ruby 2 vs. Rails 4 push for concern usage/Rails delegation

2013-06-25 Thread Matt Jones

On Jun 25, 2013, at 9:54 AM, Gary Weaver wrote:

 Just read about the Casting gem:
 
 https://discuss.gemnasium.com/t/casting-adding-behavior-to-objects-without-using-extend/34
 https://github.com/saturnflyer/casting
 
 What are the Rails core team's opinions about using Casting vs. 
 ActiveSupport::Concern usage, Rails delegation, etc.?

Seems to me like AS::Concern and Casting deal with significantly different use 
cases: modular functionality at class-load time vs. modular functionality at 
runtime.

Also, the benchmark noting the 100x speed difference compared to standard 
method dispatch is pretty hair-raising.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/groups/opt_out.




Re: [Rails-core] Possible bug in rails when I search a polymorphic association and array scope as LIKE

2013-04-08 Thread Matt Jones
There are two existing issues related to this:

https://github.com/rails/rails/issues/950
https://github.com/rails/rails/issues/7402

The code in #7402 may be helpful in your particular situation.

--Matt Jones

On Apr 8, 2013, at 2:21 AM, Alfonso Uceda wrote:

 Ok thank you, I'm going to publish in github but this bug is still in Rails 
 3.2.
 
 A greeting!
 
 El viernes, 5 de abril de 2013 19:29:14 UTC+2, Steve Klabnik escribió:
 I did not, because it should be filed on the issues tracker if it affects  
 2.3.
 
 -- 
 You received this message because you are subscribed to the Google Groups 
 Ruby on Rails: Core group.
 To unsubscribe from this group and stop receiving emails from it, send an 
 email to rubyonrails-core+unsubscr...@googlegroups.com.
 To post to this group, send email to rubyonrails-core@googlegroups.com.
 Visit this group at http://groups.google.com/group/rubyonrails-core?hl=en.
 For more options, visit https://groups.google.com/groups/opt_out.
  
  

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: [Rails-core] link_to should have its body and url arguments reversed

2013-03-15 Thread Matt Jones

On Mar 15, 2013, at 8:58 AM, Michael Grohn wrote:

 I think the link_to helper method is quite confusing with its arguments order:
 
 link_to body, url
 link_to Click me, @person
 
 Why is it thay way round? I want to make a link to [the] person, so I would 
 expect the order to be:
 
 link_to @person, Click me
 
 It reads much more natural. You don't link to [the] body, you link to 
 [the] url. So the order schould be
 
 link_to url, body, options={}
 
 Is there a rationale for the current arguments order?

I'd guess that it's because while the body is typically simple (a string or 
variable), the second argument can also be a bunch of params for url_for:

link_to 'thingy', :controller = 'wat', :action = 'huh', :protocol = 'wtf'

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: [Rails-core] link_to should have its body and url arguments reversed

2013-03-15 Thread Matt Jones

On Mar 15, 2013, at 2:39 PM, Michael Grohn wrote:

 @Matt jones
 
  I'd guess that it's because while the body is typically simple (a string or 
  variable), the second argument can also be a bunch of params for url_for: 
  
  link_to 'thingy', :controller = 'wat', :action = 'huh', :protocol = 
  'wtf' 
 
 There are 4 signatures for the link_to helper method:
 
 link_to(body, url, html_options = {})
 link_to(body, url_options = {}, html_options = {})
 link_to(options = {}, html_options = {})
 link_to(url, html_options = {})
 
 Your example would fit the second signature, which has no url argument, but a 
 url_options hash instead. This is fine, options always go at the end of a 
 method call.
 
 The first signature is the one that bothers me.

It's ultimately a matter of symmetry, especially when switching from a hash to 
a URL helper:

  link_to 'something', :controller = 'posts', :action = 'show', :id = id

becomes:

  link_to 'something', post_path(id)

Requiring that the arguments trade positions between those two lines would be 
seriously annoying.

BTW, the bikeshed should TOTALLY be painted blue. ;)

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: [Rails-core] #all changes in 4.0

2013-02-27 Thread Matt Jones

On Feb 27, 2013, at 4:42 AM, Will Bryant wrote:

 Hi guys,
 
 I don't think that the changes made to the behavior of #all in 4.0 are a very 
 good idea.
 
 I can see that you no longer need to call all in as many cases as you did 
 before - that's fine, just don't call it if you don't want it.  But that 
 doesn't mean you never need it or that people who do need it should not have 
 it available.
 
 1. Yes you can use to_a in many cases, but it behaves differently - for 
 example if you have an association, to_a will return the cached target if the 
 association has already been loaded.  You absolutely need a way to run an 
 actual query when you want the latest results.  to_a cannot be relied upon to 
 do this in all cases.

p.tasks(true) will *always* reload the association. I haven't seen the 
equivalent for relations, though.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: [Rails-core] A concern about rails validators, breaking MVC in complex projects

2013-02-22 Thread Matt Jones

On Feb 22, 2013, at 3:53 AM, dosadni...@gmail.com wrote:
 
 https://gist.github.com/bbozo/5006180
 
 This would allow us to handle highly specific controller-introduced 
 validators inside the controller and without adding unnecessary bloat in 
 other areas (usually in unit test factories and with_options :if = 
 some_roundabout_way_of_detecting_which_controller_youre_on block spam in the 
 model). 

What's wrong with something like this:

class SomeModel
  attr_accessor :validate_the_thingy

  validate :make_one_particular_and_unique_thingy_go_red, :if = 
:validate_the_thingy
end

in the controller:

@some_model = SomeModel.some_factory_method(params)
@some_model.validate_the_thingy = true


In both cases, the validation method is sitting around on the model.

I'd argue that this breaks MVC *less* than the solution in your Gist, since 
this keeps the flag separate from its implementation, rather than having the 
controller poke extra validations (by method name) directly into the model 
instance.

If you've *really* got bunches of wildly divergent validation setups, I'd agree 
with the suggestion on the ticket to actually create a (plain Ruby) mediator 
object and use the ActiveModel APIs.

--Matt Jones


-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: [Rails-core] CollectionAssociation shadows Enumerable#count

2013-02-01 Thread Matt Jones

On Jan 31, 2013, at 1:35 PM, Christian Romney wrote:

 Hi all,
 
 I realize this behavior is by design, and in some respects the right thing to 
 do. It also pre-dates the addition of Enumerable#count. I'm wondering, 
 however, if it's possible/desirable to allow the caller to access the 
 Enumerable versions under certain conditions. I originally wrote the up as an 
 issue, but was informed this would be the better venue. I'm linking to the 
 original issue on Github because the syntax highlighting is nice. 
 
 https://github.com/rails/rails/issues/9132

In the example in the issue, wouldn't this work nearly as well:

def incomplete_submissions
  submissions.to_a.count(:incomplete?)
end

In short, if you want the Enumerable behavior, just ask for it...

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: [Rails-core] Re: ActiveRecord::Persistence.increment! requires a row lock to ensure isolated updates

2013-01-23 Thread Matt Jones

On Jan 23, 2013, at 4:03 AM, Gabriel Sobrinho wrote:

 It makes sense!
 
 I have a debt entity in my application and payments this entity can happen 
 three or more times in parallel (stupid brazilian banks, don't ask me why 
 they do it).
 
 Since I have to keep a cache column of the paid value for the debt, I have 25 
 workers (sidekiq) that can call `increment!(:paid_value, paid_value)` and it 
 should keep the total paid value.
 
 I'm not sure if it will be a problem to happen something like that:
 
 debt.paid_value
 # = 100.0
 
 debt.increment!(:paid_value, 100.0)
 # = 300.0
 
 We can have problems if other columns relies on that value.
 
 Let suppose I have another column called paid_interest and with the 
 paid_value, I get the total paid:
 
 debt.paid_value
 # = 100.0
 
 debt.paid_interest
 # = 10.0
 
 debt.total_paid
 # = 110.0
 
 debt.increment!(:paid_value, 100.0)
 # = 300.0
 
 debt.total_paid
 # = 310.0
 
 The paid_interest in this case is updated in another process.
 
 It's a contrived example but if that's the case, I will need to reload the 
 entire record to get the right total paid.
 
 At least some documentation telling that increment and increment! are subject 
 to race conditions is needed.

I believe the suggested solution in this case is to use optimistic locking (via 
a lock_version column) and then handle collisions manually.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] Re: Re-imagined README.md for rails applications

2013-01-01 Thread Matt Jones

On Jan 1, 2013, at 8:08 PM, Ryan Bigg wrote:

 I think that this is something that would differ incredibly from app to app. 
 For instance, I would not install Ruby using apt-get myself.
 
 While I like the idea of having it be a Getting Started doc for an app, I 
 don't think that Rails could come with a cohesive default that would work for 
 everyone.
 
 -1 to this change.

As a more general comment, if something like this was to be added I think it's 
important to decide what the expected audience for the README is. For instance, 
definitions of Rails terms and instructions on how to install Ruby and 
webservers are probably overkill if the audience is developers new to the app 
but not to Rails.

One thing that might be useful - somehow hook into the various choices 
available in `rails new` (test framework, ORM, etc) and include details in the 
generated file. So for instance, selecting Rspec would produce a paragraph 
about how to run the specs.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] Suggestion: default values for models

2012-10-18 Thread Matt Jones

On Oct 18, 2012, at 8:50 AM, Gabriel Sobrinho wrote:

 That is a problem for me either.
 
 I can't use before_save callback because I need to show the default value on 
 forms.
 
 So, I have a date field and the default value is today, but when user open 
 the form, today must be on that field.
 
 
 I'm setting this kind of default value on controller like that:
 
 def new
   @payment = Payment.new
   @payment.date = Date.current
 end

One method I was surprised to not see on Stack Overflow - overriding the 
accessor:

class Payment  AR::Base

  def date
super || write_attribute(:date, Date.current)
  end

end

This still has the issue identified by G. Sobrinho, however, where explicitly 
setting an attribute to nil doesn't work quite right.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



[Rails-core] Approximate release timeline for Rails 4?

2012-09-30 Thread Matt Jones
Is there any targeted date for release of Rails 4? Best I could find Googling 
was in 2012, but that could mean anything from days to months.

Asking because I've been running across some obscure bugs 
(https://github.com/rails/rails/issues/7809 for instance) in the course of a 
larger patch, and am curious if it would be better to split the bugs out as 
individual issues (happens sooner) or fix them in a bigger patch (takes longer).

Thanks,

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] Partials and helpers

2012-09-05 Thread Matt Jones

On Sep 5, 2012, at 8:47 AM, Luís Ferreira wrote:

 Hi,
 
 Is there any reason why helpers cannot render partials?
 
 I would like to do something like this in the layout:
 
 body
  %= magic_header %
 
  %= yield %
 /body
 
 and then have a magic_header helper
 
 def magic_helper
  ...do some magic...
  render partial: magic_helper
 end
 
 Why is this wrong?

What's it failing to do? I've used this pattern frequently for partials that 
need some extra argument preprocessing and haven't encountered problems.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] Activerecord: how to write a new feature?

2012-08-11 Thread Matt Jones

On Aug 11, 2012, at 6:23 PM, Rafael Almeida wrote:

 On Friday, August 10, 2012 5:50:58 PM UTC-3, EMoreth wrote:
 Try this:
 
 Project.joins(:services).where(:services = { :id = [1,2] 
 }).group(:id).having(count(*) = 2).all
 
 This produces to me:
 
 SELECT `projects`.* FROM `projects` INNER JOIN `services` ON 
 `services`.`project_id` = `projects`.`id` WHERE `services`.`id` IN (1, 2) 
 GROUP BY id HAVING count(*) = 2
 
 Which returns me only the projects who are associated to both services 1 and 
 2.
 
 Indeed that does the trick. Nice thinking. It's probably even better than the 
 intersection approach from SQL point of view.
 
 Anyway, the reason we don't have  and | operators in activerecord is that 
 it's believed that there's always a better way to write a query not using 
 them? 

I'd say it's more that it's phenomenally difficult to come up with a *generic* 
method that will transform (for instance) your two queries:

Person.joins(:services).where('services.type' = 1)
Person.joins(:services).where('services.type' = 2)

into the final query.  Note that the suggestion above is only correct if you 
never have Project with two links to the same service. Based on the what you've 
described about your domain, this is probably a sensible assumption - but the 
general case wouldn't necessarily be able to assume that.

Full support for 'or' is a similar problem - there's a first-draft here:

https://github.com/rails/rails/pull/6817

but that code isn't going to work correctly for anything but fairly similar 
queries; joins, selects, etc all go out the window.

--Matt jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] ActionController::TestCase controller construction

2012-07-29 Thread Matt Jones

On Jul 28, 2012, at 11:44 PM, Aaron Patterson wrote:

 In the case a developer has not constructed a controller, the setup
 method of ActionController::TestCase will attempt to construct a
 controller object.  If it cannot construct a controller object, it
 silently fails.
 
 I added a warning in this case, and I'd like to eventually deprecate the
 behavior.  I can't think of why anyone would want to use
 ActionController::TestCase and *not* test a controller.  Does anyone
 know a reason *why* we would do this?
 
  
 https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/test_case.rb#L534-542

Maybe I'm missing something, but doesn't the call to 
setup_controller_request_and_response happen *before* any user-defined setup 
methods get called? In that case, it's intended to let users do unusual things 
(that don't set, or set to nonsense, controller_class) and then set up their 
own controller object.

There are some related commits that seem relevant:

https://github.com/rails/rails/commit/13950a8cc94ab93bb20976f2797b1df9740849b3
https://github.com/rails/rails/commit/ee82e1c3015392c87c88ee32003763210a75d1ec
https://github.com/rails/rails/commit/529a3ee50eeb7db5a78afeb5da38fd71b42e7ea2

I'd say there's a good chance that all of these changes are intended to support 
doing things like this:

https://www.relishapp.com/rspec/rspec-rails/docs/controller-specs/anonymous-controller

by handling the case where the controller-under-test isn't a named constant.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] Behavior of first_or_create

2012-07-25 Thread Matt Jones

On Jul 24, 2012, at 5:42 PM, Jon Leighton wrote:

 On 24/07/12 21:29, Matt Jones wrote:
 
 
 Nope, that's not exactly what I observed; I'll try again. That code *does* 
 call the create correctly, if there are no users with the correct 
 first_name. The confusing part to me was that it wasn't quite the same as 
 this:
 
 User.where(:first_name = 'Scarlett').find_or_create_by_last_name(O'Hara)
 
 The latter includes a condition on last_name in the find, where the former 
 does not.
 
 This behaviour is intentional. The dynamic version did actually previously 
 take an options hash of stuff that would get passed to create. So:
 
 User.where(:first_name = 'Scarlett').find_or_create_by_last_name(O'Hara, 
 :age = 32)
 
 would do:
 
 User.where(:first_name = Scarlett, :last_name = O'Hara)
 
 and then:
 
 User.create(:first_name = Scarlett, :last_name = O'Hara, :age = 32)
 
 I believe the rationale is simply that you can put all of your conditions in 
 a where()

Who's got two thumbs and didn't know about this feature? THIS GUY! :)

I also noted, after actually RTFM, that this works too:

User.find_or_create_by_last_name(:last_name = O'Hara', :age = 32)

where the named parameter in the dynamic matcher is selected out of the hash 
that's passed in.

Any objections to adding an explicit converting from dynamic finders section 
to the documentation for first_or_create? I'll try to get something together 
this weekend.

Thanks,

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



[Rails-core] Behavior of first_or_create

2012-07-24 Thread Matt Jones
I just ran across a weird glitch (IMHO) in find_or_create. The arguments passed 
to it are *not* added to the conditions for the 'first' part. This is odd, 
given that it's intended to replace find_or_create_by_* methods, which *did* 
use the specified values as conditions.

I'm unsure on whether this behavior is entirely undesirable, but it's 
definitely not what I had expected in my use case (ensuring that a join table 
record exists). Perhaps there should be a variant (find_or_create_exactly, 
perhaps?) that uses the supplied attributes as additional conditions. 

If nothing else, the documentation should be updated to reflect this scenario - 
the last case in the examples *almost* describes this scenario, but the block 
form used there makes it unclear what:

User.where(:first_name = 'Scarlett').first_or_create(:last_name = O'Hara)

would do. 

I also found that DataMapper implements the behavior I was expecting in their 
first_or_create method:

https://github.com/datamapper/dm-core/blob/master/lib/dm-core/model.rb#L448

Thoughts?

--Matt Jones


-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] Behavior of first_or_create

2012-07-24 Thread Matt Jones

On Jul 24, 2012, at 4:04 PM, Andrés Mejía wrote:

 I would definitely expect
 
 User.where(:first_name = 'Scarlett').first_or_create(:last_name = O'Hara)
 
 to call
 
 User.create(:first_name = 'Scarlett', :last_name = O'Hara)
 
 if that's not what's happening then I think it's a bug and should be fixed. 
 Matt, do you have a minimal app that shows the problem? I would like to write 
 a test case for Rails that shows this strange behavior.

Nope, that's not exactly what I observed; I'll try again. That code *does* call 
the create correctly, if there are no users with the correct first_name. The 
confusing part to me was that it wasn't quite the same as this:

User.where(:first_name = 'Scarlett').find_or_create_by_last_name(O'Hara)

The latter includes a condition on last_name in the find, where the former does 
not.

Given that the dynamic form is deprecated (targeted for removal in 4.1 - see 
active_record_deprecated_finders for details), it's worth either matching the 
old behavior or clearly documenting the difference to avoid confused upgraders.

--Matt Jones


-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] sti_object.becomes(Parent) unexpectedly mutating the receiver

2012-07-20 Thread Matt Jones

On Jul 20, 2012, at 5:48 PM, Peter Brown wrote:

 I ran into an interesting issue today with ActiveRecord's becomes method and 
 discovered that it is mutating the receiver without me knowing it. 
 
 The API docs say 
 
 The new instance will share a link to the same attributes as the original 
 class. So any change to the attributes in either instance will affect the 
 other.
 
 However, it doesn't say that the type attribute is changed on the receiver 
 just by the method call. 

'type' is an attribute; it gets changed - and the docs say the changes will 
happen to both. A bit unclear, but not a bug.

Definitely worth an update to the documentation, though.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] attr_accessible on some properties + attr_protected on others makes class 'open-by-default'

2012-07-10 Thread Matt Jones

On Jul 10, 2012, at 12:29 PM, Prem Sichanugrist wrote:

 Yeah, Jay. Your solution won't work with inheritance.
 
 By deprecating the attr_protected, you can allow most of the attributes 
 anyway (but seriously seriously seriously discouraged) by do something like:
 
attr_accessible columns - [:created_at, :updated_at]

Note that this may die in exciting ways if you put it in a model that hasn't 
been created in the DB yet. (since columns looks at the table metadata)

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] Defining #blank for Array.

2012-07-09 Thread Matt Jones

On Jul 9, 2012, at 10:15 AM, Michael Boutros wrote:

 Hello:
 
 1.9.3p194 :014  .blank?
  = true 
 1.9.3p194 :015  [, ].blank?
  = false 
 
 Proposal: the second line should also produce true.
 
 Thoughts?

If you really want to check for are all the values in this array blank, try:

some_array.all?(:blank?)

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] ActiveRecord update_attribute vs update_attributes

2012-06-14 Thread Matt Jones

On Jun 14, 2012, at 12:36 PM, Brian Morearty wrote:

 Steve,
 
 It'd be cool if the patch included the addition of a :validate = false 
 option in update_attributes.
 
 This would make for an easier upgrade path from update_attribute.

Note that there's one additional difference, due to attribute whitelisting. 
Thus:

some_object.update_attribute(:foo, 'bar')

is NOT the same as:

some_object.update_attributes(foo: 'bar')

if foo isn't mass-assignable.

Not sure if it's terribly relevant, but worth mentioning.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] Making touch more efficient

2012-06-07 Thread Matt Jones

On Jun 7, 2012, at 6:55 PM, Spike wrote:

 I'm currently working on a Rails 2.3 project but I think the code hasn't 
 changed much around touching in the latest release so here goes:
 
 Touching seems to be less efficient than it could be. Currently it seems to 
 change the updated_at (or other) field, save the whole object, trigger all 
 callbacks on that object (some of which might be to touch other associated 
 objects) and so on.
 
 Seems to me that there could be performance gains made (especially when it 
 comes to deleting and cloning deeply nested relational structures) by making 
 touch only update_attribute the appropriate fields, and then only call the 
 associated touch callbacks (because they're already named well they can be 
 identified) and so on.
 
 Is there a reason why it's not does this way already?

The implementation in Rails 3 is entirely different:

http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-touch

It now skips all the callbacks, etc entirely.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] Nested Resource Route Helpers

2012-06-05 Thread Matt Jones

On Jun 5, 2012, at 8:18 AM, John Mileham wrote:
 
 It's easy to dismiss as an obvious mistake, but I've seen it done too many 
 times to want to encourage deeply nested routes by automating the URL 
 generation.  If your controller is forced find the user from the project in 
 order to perform access control, then the odds of making a mistake are much 
 lower:
 
 dev create
   @project = Project.find(params[:project_id])
   raise alert!! unless @project.user == current_user

Curious - is there a reason to prefer this code to the alternative:

@project = current_user.projects.find(params[:project_id])

which turns attempts to access other's projects into 404s?

--Matt Jones


-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] Attribute query methods and semantics

2012-06-01 Thread Matt Jones

On May 31, 2012, at 8:58 AM, Maksym Melnychok wrote:

 Does anyone else finds attribute query methods semantically confusing?
 
 Hi,
 
 Consider this code:
 
 post = Post.new(:visible = true, :url = http://com;)
 
 if post.visible?
   puts ima visible!
 end
 
 if post.url?
   puts ima url! (wait wat? o_0)
 end
 
 Does this feel right to you? In case with post.url? i read it as Hey post 
 object, are you an url? which is apparently not what the code will do.
 
 So it seems like semantically perfect flag checks go together with totally 
 confusing(for a reader) way of checking whether an attribute is present or 
 not.
 
 I would generate attribute query methods only for boolean attributes.

One use that hasn't been mentioned previously - passing method names to things 
like :if, :unless etc in validations. With the ? version, this can be pretty 
short:

validates_presence_of :some_attribute, :unless = :some_other_attribute?

The no-? version doesn't do the right thing in many cases (since empty strings 
evaluate to true), and using present? instead requires a Proc.

Not certain if this is a sufficient argument for the existence of the ? suffix, 
but worth thinking about.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] Re: Support the ability to write properties within models

2012-05-10 Thread Matt Jones
I'm one of the maintainers of the hobofields gem Andrew Mutz mentioned earlier, 
so I figured I'd toss my observations in.

To me, an in-model DSL provides two major benefits:

- enhanced readability of the class, both for the developer and for other code. 
For instance, compare these two models (loosely extracted from an old Rails 2.3 
app of mine):

class CertificationPayment  ActiveRecord::Base

  validates_numericality_of :year, :only_integer = true, :greater_than = 2000

  belongs_to :detail, :class_name = 'CertificationDetail'
  
end

VS

class CertificationPayment  ActiveRecord::Base

  fields do
year   :integer
contact_number :phone_number
payment_method :payment_method
check_number   :string
amount :decimal, :scale = 2, :precision = 10
timestamps
  end

  validates_numericality_of :year, :only_integer = true, :greater_than = 2000

  belongs_to :detail, :class_name = 'CertificationDetail'
  
end

I believe most developers would regard the second form as more understandable, 
especially if they were new to the codebase.

In the case of hobofields, there was the additional need to have more-specific 
type information for use by code that essentially generates forms on-the-fly at 
application load time. This arguably makes it *more* database-agnostic, since 
code that reflects on field types isn't tied to ActiveRecord::Base.columns.

- The second motivation was to provide a richer type system for fields than 
would otherwise be available. For instance, two of the fields in the example 
above use application-defined types (:phone_number and :payment_method). 
Underneath the hood, both fields eventually wind up as plain :string columns in 
the DB, but this interface allows the developer to be more specific in the 
description.

In addition, the rich types can provide additional validation, normalization, 
and formatting capability - :phone_number, for instance, normalizes whatever 
the field is set to to remove punctuation, validates that the resulting string 
is the correct number of digits, and formats the data back into US format for 
display. None of this is particularly amazing - but the truly handy thing with 
rich types is that it is modular - changing an application to store / format 
non-US phone numbers with this method would be a matter of redefining the type, 
not rewriting validations in many places. Validation objects can certainly 
streamline this in plain AR, but you still need to remember to use them every 
time you have a model that uses that type.



Regarding migration generation, the hobofields gem takes a somewhat deeper 
approach. Our migration generator does the following:

- ignores models without a 'fields' block. This avoids the gotta use it 
everywhere problem.

- interactively prompts the user to decide between removing things vs. renaming 
things, since it's not possible to determine which action is correct in most 
cases.

- has the option to either generate the migration and run it, or just generate 
it. This allows for the addition of data conversion code, DB-specific setup (FK 
constraints, etc) and full user control over the migrations if desired.



Regarding the developer beholden to an ivory tower of DBAs issue, I'd say 
this sort of thing is *still* useful, even if it isn't generating the 
migrations. It provides an executable contract asserting what the code is 
expecting from the DB; anybody who's ever pulled down a branch only to discover 
that their development DB is out-of-sync with the code would likely appreciate 
that.



Short story shorter (too late) - I'm not sure this is something that's yet 
ready to be baked into Rails; hobofields in particular could use a good spring 
cleaning and refactoring, now that it's been in production use for a couple 
years. Anybody who's interested in discussing *that* further is welcome to join 
us over in the hobo-dev Google Group.

Thanks,

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] Scaffold Generator Woes

2012-03-08 Thread Matt Jones

On Mar 8, 2012, at 5:25 PM, Everton Moreth wrote:

 Agreeing with José, I work on a University, and we try to keep all our 
 systems follow a pattern, so clients get used to our layout and design and 
 our developers get standard comment tips about how to name and describe 
 methods. For this, we rely strongly on scaffold customization.
 
 I also agree that this should not be put as an advantage for beginners on 
 tutorials and books, showing them how to not write code. Even a warning 
 message could appear on scaffolding generation, or making the generators a 
 little less automagic (and maybe a little more dumb also), forcing people 
 to customize scaffolds before getting something usable.

WAT.

No, seriously - this is like a group of Ikea craftsmen deciding to no longer 
use pre-cut wood, since making customers cut it for themselves will teach them 
carpentry more quickly. Dumbing down the generator is them trying to split 
the difference by cutting to shape but not drilling holes; both approaches 
ignore that the EAT UR VEGGIES NAOW method only works if you've got customers 
that can't choose an alternative.

To me, it seems easier to imagine the counterfactual: imagine Rails *without* a 
similar generator, and then imagine the responses to a proposed generator that 
would automatically create reasonably clean, idiomatic code that a new 
developer could quickly see results from. Such a thing would likely be 
popular...

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] ActiveResource 3.2.1 : ActiveResource::Formats::JsonFormat.decode and ActiveResource::Base.include_root_in_json

2012-03-03 Thread Matt Jones

On Mar 2, 2012, at 10:17 PM, Mark Peterson wrote:
 
 ### Scenario 2 using remove_root in decode, user.json does not have id ###
 
 def decode(json)
   Formats.remove_root(ActiveSupport::JSON.decode(json))
 end
 
 GET /users/123.json
 
 {\image_page\:{\images\:[{\id\:123},{\id\:456}],\total\:2000,\count\:2,\start_index\:0}}
 
 p user = #User:0x0101133cb8 
 @attributes={images=[#Image:0x01011327a0 @attributes={id=123}, 
 @prefix_options={}, @persisted=false, #Image:0x0103a49e40 
 @attributes={id=456}, @prefix_options={}, @persisted=false], 
 total=2000, count=2, start_index=0}, @prefix_options={}, 
 @persisted=true

This looks to be a variant of issue #2692:

https://github.com/rails/rails/pull/2692

although the patch in that instance wouldn't fix this bug, as the detection 
heuristic will guess that image_page is a root element to be removed.

It appears that the problem is that remove_root doesn't have any awareness of 
the context in which it's operating - really, we should only be removing the 
appropriately-named root element (if it exists).

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] [ANN] Rails 3.2.2.rc1, 3.1.4.rc1, and 3.0.12.rc1 have been released!

2012-02-23 Thread Matt Jones

On Feb 22, 2012, at 4:03 PM, Aaron Patterson wrote:

 Hi everyone,
 
 I just released the following Rails release candidates:
 
  * 3.2.2.rc1
  * 3.1.4.rc1
  * 3.0.12.rc1
 
 Please give these releases a try!  Make sure to report any regressions from 
 the past release to the [ruby on rails core mailing 
 list](http://groups.google.com/group/rubyonrails-core).
 
 If there are no show stopping regressions reported, I'll release the final 
 versions on Monday.  This is your opportunity to prevent me from releasing a 
 version that breaks your app!  Please use this opportunity! :-D

It would be great to get this patch in:
https://github.com/rails/rails/pull/4881

Does it count as a regression if ARes has *never* been able to parse the 
default Responder's error messages?

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



[Rails-core] Using JSON template builders with respond_with

2012-02-13 Thread Matt Jones
Quick question: what's the best way to use a JSON template builder (jbuilder, 
etc) with respond_with? The current implementation loses some of the semantics 
in that situation; for instance, adding a template for the create action means 
that the response comes back as a 200 OK instead a 201 Created.

Is there a clean way to handle this? I like the idea of avoiding hackery like 
including view helpers in models for as_json, but the response code changes 
mean that I'm back to writing out respond_tos manually.

Thanks,

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



[Rails-core] Interoperating ActiveResource and ActionController::Responder

2012-02-04 Thread Matt Jones
I've just created a pull request to finally make ActiveResource correctly 
handle validation errors returned from ActionController::Responder's default 
JSON handling code. The code also handles the format produced by pre-3.2 
Responders *and* the format previously expected by ActiveResource, so it 
shouldn't break in any application that was working before.

https://github.com/rails/rails/pull/4881

Would appreciate any feedback - it would be nice for the framework to actually 
work with its own API endpoints...

Thanks,

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] Pull request: fix SQL generation bug in Postgres / Oracle

2012-01-03 Thread Matt Jones

On Dec 28, 2011, at 5:55 AM, Jon Leighton wrote:
 
 As a side-effect of that
 implementation, this code:
 
 SomeModel.order('foo ASC').reorder('bar DESC').order('baz ASC')
 
 does not (as might be expected) sort the returned record by baz - the
 reorder overrides all previous *and* subsequent orders.
 
 I think this is a bug.

Here's a pull request to correct this behavior:

https://github.com/rails/rails/pull/4282

This also solves the original problem in a slightly different way - a 
relation's order_values attribute is now always the ordering the final relation 
will use.

--Matt Jones

PS:
I also noticed a tangentially related issue - reverse_order has a similar sort 
of issue with late-application; for instance, this:

SomeModel.order('foo ASC').reverse_order.order('bar ASC')

will wind up with an order of 'foo DESC, bar DESC' since the reverse isn't 
handled until build_arel is called...

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] Pull request: fix SQL generation bug in Postgres / Oracle

2011-12-28 Thread Matt Jones

On Dec 28, 2011, at 5:55 AM, Jon Leighton wrote:

 On 27/12/11 14:32, Matt jones wrote:
 https://github.com/rails/rails/pull/4082
 
 I've commented on the PR.
 

Updated PR against master: https://github.com/rails/rails/pull/4216

 On a related note, the current mechanism for handling 'reorder' seems
 pretty strange; what's the design motivation behind keeping the values
 passed to reorder separate from order?
 
 The reason is so that we can handle eagerly defined scopes correctly. For 
 example, consider:

That makes sense. I was pretty sure there was a good reason. :)

 The root problem is that we allow eagerly evaluated scopes to be defined at 
 all. Personally I dislike 'scope' and would rather that we just told people 
 to define their own class methods (which of course only get evaluated when 
 they are actually used). Others like the brevity of the single line 'scope' 
 syntax.

IMO, the real issue with order/reorder here is more about encapsulation - 
currently, anyone who's digging in the Relation internals needs to know what to 
do with order_values vs. reorder_value. It doesn't actually happen everywhere - 
for instance, in find_one:

https://github.com/rails/rails/blob/master/activerecord/lib/active_record/relation/finder_methods.rb#L321

the giant conditional skips checking reorder_value. Probably not a major issue 
(especially since it can only matter if the identity map is on), but still 
annoying...

 For Rails 4 I would like to discuss making use of the new lambda syntax as a 
 compromise, e.g.
 
 scope :by_bla, - { reorder('bla') }

Seems sensible to me. I've also encountered a related issue with merging 
scopes; in short, merging a scope defined with a lambda has to *also* be 
wrapped in a lambda or else things don't work as intended. For instance:

scope :recent, lambda { where('created_at = ?', 5.days.ago }
scope :recent_sorted, merge(recent).order('some_field ASC')

winds up prematurely evaluating the recent scope. Not a huge deal when the 
scopes are defined close to each other, but a recipe for head-scratching when 
they're farther apart (or in different modules, etc).

 As a side-effect of that
 implementation, this code:
 
 SomeModel.order('foo ASC').reorder('bar DESC').order('baz ASC')
 
 does not (as might be expected) sort the returned record by baz - the
 reorder overrides all previous *and* subsequent orders.
 
 I think this is a bug.

I'll write up a test and a ticket to get that discussion started.

Thanks,

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



[Rails-core] Pull request: fix SQL generation bug in Postgres / Oracle

2011-12-27 Thread Matt jones
https://github.com/rails/rails/pull/4082

Can I get some eyes on this? It's a relatively trivial change, but
without it Oracle and Postgres generate invalid SQL in particular
cases.

TL;DR version: the construct_limited_ids_condition function passes the
order parameters from the relation to the adapter's 'distinct' method,
but it ignores values set with 'reorder'.

More detail:
On Postgres and Oracle (perhaps others), columns used in the ORDER BY
clause must appear in the SELECT DISTINCT clause or the SQL is
invalid. In the pull request's test, this code:

author.posts_with_comments_sorted_by_comment_id.where('comments.id 
0').reorder('posts.comments_count DESC', 'posts.taggings_count
DESC').last

generates the following SQL without the patch:

SELECT DISTINCT posts.id, comments.id AS alias_0 FROM posts LEFT
OUTER JOIN comments ON comments.post_id = posts.id WHERE
posts.author_id = 1 AND (comments.id  0) ORDER BY
posts.comments_count ASC, posts.taggings_count ASC LIMIT 1

Note that generated SELECT clause references the wrong order, while
the ORDER BY clause is correct.

On Oracle, the situation is even worse - there, the generated SQL
actually references the aliases from the SELECT and either silently
fails (sorting on the wrong thing) for a single column in the reorder,
or blows up with an error if the count of terms in 'order' and
'reorder' differ.

The patch fixes the issue by using whatever's been passed to reorder
to build that SQL - a pretty minor change.

On a related note, the current mechanism for handling 'reorder' seems
pretty strange; what's the design motivation behind keeping the values
passed to reorder separate from order? As a side-effect of that
implementation, this code:

SomeModel.order('foo ASC').reorder('bar DESC').order('baz ASC')

does not (as might be expected) sort the returned record by baz - the
reorder overrides all previous *and* subsequent orders.

Thanks,

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



[Rails-core] ActionView::OutputBuffer - append= and are not QUITE identical

2011-10-09 Thread Matt Jones
Not sure if this is the right place for this, but it's certainly to do with 
core Rails and only of interest to pretty hard-core framework hackers...

Anyways, the issue I ran into was that aliasing a method () to a setter 
(append=) doesn't quite work the way you'd expect. For instance:

x = ActionView::OutputBuffer.new('something')
result1 = (x  ' else ') # = 'something else'
result2 = (x.append= ('entirely')) # = 'entirely'

In the second example, the return value from the call is the value that was 
passed in (Ruby's standard behavior for assignments in general). The return 
value of append= is silently dropped on the floor.

Note that this will never be observed by users of the built-in ERB template 
parser, since it automatically grabs @output_buffer in the Erubis postamble.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] Date#- = Rational ?

2011-04-06 Thread Matt Jones

On Apr 6, 2011, at 11:18 AM, Robert Pankowecki wrote:

 ruby-1.9.2-p136 :080  Rails.version
 3.0.6
 
 ruby-1.9.2-p136 :081  (Date.today - Date.today).class
 Rational  Numeric
 
 Why is the difference Rational ?

This is actually a feature of the built-in date library; I get the same result 
on 1.8 in vanilla irb (after doing require 'date'). It's intended (AFAIK) to 
enable sensible operations between Date and DateTime objects, since subtracting 
Dates gives a value which should be read as number of days and DateTimes can 
mix fractions in:

require 'date'
d = Date.civil(2011,4,6)
d2 = DateTime.civil(2011,4,6,12,0,0)

d2 - d # returns Rational(1,2) - in other words, half a day since the docs 
say Date objects are considered to have a time of midnight

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] Problem in saving fields to database from csv using fastercsv

2011-03-23 Thread Matt Jones

On Mar 23, 2011, at 9:42 AM, Surya wrote:

 Hi,
 
 First of all very sorry for this long post. I am trying to save my csv data 
 to table items which is associated with Item model.
 
 This is what my csv have:
 'name';'number';'sub_category_id';'category_id';'quantity';'sku'; 
 'description';'cost_price';'selling_price'
 'Uploaded Item Number 1';'54';'KRT';'WN';'67';'WNKRT0054';'Some Description 
 here!!';'780';'890'
 'Uploaded Item Number 2';'74';'KRT';'WN';'98;'WNKRT0074';'Some Description 
 here!!';'8660';'9790'
 
 First row show the fields for items table.
 
 Here I am using fastercsv to process my csv and paperclip to upload.
 
 I am able to process file read content and able to fill up the field too here 
 is the processing code:
 
 def proc_csv
 @import = Import.find(params[:id])
 @lines = parse_csv_file(@import.csv.path)
 @lines.shift

As others have pointed out, this isn't the right place for this. In any case, I 
suspect your issue is that Excel has spit out a UTF-16 file and you didn't tell 
whatever's parsing it about that...

--Matt Jones


-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



Re: [Rails-core] ActiveResource: prefix attributes that are mass assigned are not readable - Stale ?

2011-03-18 Thread Matt Jones

On Mar 18, 2011, at 1:21 PM, Pierre Lancien wrote:

 Hi,
 
 I noticed that 2 days ago that this ticket was marked stale.
 
 https://rails.lighthouseapp.com/projects/8994/tickets/6171
 
 But the issue is still here (I checked just now), and it reminded me I
 had a patch for it I forgot to submit, so I attached the patch file to
 the ticket.
 
 Since I'm still new on this, can someone please point me the right
 procedure ? Should I have opened a new ticket ? Should I have changed
 the tags associated to the ticket (I don't know how to do it) ?
 Any help appreciated.

Ticket reopened.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Core group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.



  1   2   >