Thanks for the feedback/education. On Sat, Sep 26, 2009 at 2:06 PM, Jeremy Evans <[email protected]>wrote:
> > On Sep 26, 8:49 am, David Jenkins <[email protected]> wrote: > > I did some research into hashes, and sure enough this is the default > > behavior: aHash[:nonexistentkey] returns nil. I then found this at > > stackoverflow: > http://stackoverflow.com/questions/164714/how-can-i-use-c-style-enume... > > > > <http://stackoverflow.com/questions/164714/how-can-i-use-c-style-enume.. > .> > > specifically, > > > > STATES = Hash.new { |hash, key| raise NameError, "#{key} is not allowed" > } > > > > STATES.merge!({:open => 1, :closed => 2, :max => 3, :min => 4}).freeze() > > > > STATES[:other] # raises NameError > > > > I tried this (*omitting the .freeze() since it adds extraneous elements > to > > our discussion)*, and it worked as expected, i.e., raised an error when > > referencing STATES[:other]. I would think this would be a great > time-saver > > to have in Sequel, given that typos happen and even at runtime they won't > > reveal themselves in the current setup. > > > > Again, being a ruby newb, I'd love to hear other thoughts on this issue. > > No, I don't think this is a good idea. Beyond breaking backward > compatibility, it goes against standard ruby behavior. If you want an > error raised for a nonexistent key, you use Hash#fetch. > > I'm sure it takes some getting used to if you come from a static > language where the compiler would catch similar errors (or python, > where it causes a KeyError). However, it's not generally an issue for > experienced ruby programmers. > > BTW, your problem would have been easily caught by most of the people > that responded to this thread if you didn't "clean up" the code. In > the future, just paste what you have verbatim. > > The great thing about ruby is that it's easily possible to have the > behavior you desire by adding it yourself. For a single dataset, you > could do: > > def dataset.fetch_rows(*args) > h = Hash.new { |hash, key| raise NameError, "#{key} is not > allowed" } > super(*args){|r| yield h.merge(r)} > end > > For all datasets for a given database: > > def DB.dataset(*args, &block) > dataset = super > def dataset.fetch_rows(*args) > h = Hash.new { |hash, key| raise NameError, "#{key} is not > allowed" } > super(*args){|r| yield h.merge(r)} > end > dataset > end > > Jeremy > > > --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "sequel-talk" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/sequel-talk?hl=en -~----------~----~----~----~------~----~------~--~---
