How to return untranslated keys - ruby-on-rails

For an API, I want to return the actual keyified string.
So:
User.errors.messages[:name]
#=> activerecord.errors.models.user.attrributes.blank
Instead of
Can't be blank
I know I can override this by creating an actual translation, or by setting custom errors in the validates methods in my Models, but I was wondering if there is a lower level, simpler way to make rails return the "keyified" string instead of parsing it through the translation-layers.

I answered some similar questions on SO, but could not find them right now...
I think that this is not possible right now because the ActiveModel::Errors::add method does not store the Key to the message, but just the derived message.
It's also not trivial to reverse get the key from translation files or the like.
I think it would be a valuable addition to rails to actually store the key of the error-message instead of just the message itself.

Related

Trick when dynamically appending GET attributes

When dynamically building SQL queries you often see something like this:
WHEN 1=1 AND title="Example" AND ...
The purpose of the 1=1 is to be able to keep appending AND-statements without having to check if any previous statements exist. Thereby avoiding something like this happening:
WHEN AND title="Example" AND ...
I quite often come across a related issue when building the the attributes/search-query for a GET request. I don't want to keep checking if I need to prepend the attribute with '?' or '&'.
So my question is, is there any 'safe' way for me to add an initial attribute that won't interfere with any potential software on the server side. Assuming I do not have full knowledge of the backend.
Something like:
http://example.com?1=1&title=example
http://example.com?null&title=example
http://example.com?i-am-useless&title=example
Or is this allowed?
http://example.com?&title=example
Is there perhaps a simpler way to solve this?
Make sure the URI-string you want to add parameters to already ends in a '?'. Then for every key-value pair, add 'key=value&' to it. Optionally you can then in the end delete the last character from the resulting string. - Reddit user omepiet

Hide/truncate long attributes in rails console

For a blog model I'm saving an RSS field as text under Blog.rss, problem is, some of this is rather long and each one prints when I'm working in the rails console, ie: Blog.last(10).
Is there a way to hide output unless I call someblog.rss specifically?
I had a similar problem and received some solutions in another forum, which were:
Use select to get just the columns you need
If you have a very long column (I had JSON data structure from a webhook cluttering the console), consider whether you really need it, and if you don't , don't store it in the table
Or, consider storing it in an associated table
if you need the whole object but just want to change how it's represented in console/log output, you can redefine inspect
yourobject.as_json(except: :unwanted_column)
Also
You could look into: https://github.com/awesome-print/awesome_print

Rails - best practice to store dictionaries (key value pairs)

I need some architectural advice. I'm more into java, but trying to get up to speed with Ruby-on-rails. In the app I am building I need a convenient place to store some dictionary values that will be later used in various places of the application. These will be usually key value pairs - e.g. list of values to be used in select list.
The main objective is to keep this logic in one place of the application.
I am considering following options:
Store values in the database - i'm kind of reluctant from that, as values won't change very often.
Put all of the values in one class. In JAVA I'd have some static properties in one class holding this values (e.g. call Utils.getStates() will return list of states). How to do it ruby way?
Have some .yml file with values - read from the values. How to do it? I guess I have to parse the file in the initializer, but is there any tutorial how to do it?
Precise example? Let's say that have a model that have a field called "Type". Type can be: ['Type A', 'Type B', 'Type C'...]. And of course, for each type I want to have key and value.
I'd appreciate some suggestions about how you solve this problem in your apps.
Thanks,
Maciek
How often does the list change? Is it acceptable to have developers involved each time a value changes (updating code, re-deploying the app)? If the answer is no then store the values in a database.
Is the list of values reuseable? Then a gem or a yaml file with an initializer might be a good choice.
Is it just a small list and does not change often? Then you might want to consider a constant.
I think in Rails any data that would change at runtime and needs to be persisted, would normally be stored in the database. I think that would be the "rails way". You could save the data to yaml or json file, but that would not follow the normal flow of the MVC pattern that is so common in rails

How can I map/link/associate a UUID to a random hex number

Newbie here, wrapping my head 'round this stuff!
I'd like to use the hex number as my url (external identifier) and keep the uuid within the database for a ruby on rails application. Is this even possible?
Thanks a bunch
Many people advise you against it but, yes, it is possible. It will need some code for it, and the solution depends on which version of Rails you use and what you use for the database, which is why I'm going to answer in a generic way.
You will want to have two different fields for the model: one for the external hex representation and another one for a separate UUID. Then, you can use the hex string to find instances in your controller actions, for example.
Please take a look at the following (they don't seem to have the two fields but will point you to the right direction anyway):
Problems setting a custom primary key in a Rails 4 migration
Change Primary Key Issue Rails 4.0
http://www.speakingcode.com/2013/12/07/gracefully-using-custom-primary-keys-in-rails-4-routes-controllers-models-associations-and-migrations/
And a longer post of a similar thing to do: http://ruby-journal.com/how-to-override-default-primary-key-id-in-rails/
Also, the FriendlyId gem might do what you want.

How can I most efficiently iterate over a hash of hashes in order based on key value in inner hash?

I've got a JSON hash of hashes returned by a website API that I want to parse and display based on a specific key's value within the internal hashes.
I can think of solutions that would achieve this, but they would take a number of lines of code and don't seem efficient. Surely there must be a way to natively in Rails, given the focus on convention over configuration. I've googled around a bit, but found nothing that covers this issue.
Sample Response from API:
[{"banner":"01197271","birthday":"1991-01-11","committee_id":1,"created_at":"2012-08-08T01:56:02-05:00","email":"me#example.com","first_name":"Dan","graduation_date":"May 2013","hometown":"San Antonio","hours_enrolled":15,"id":2,"image":{"url":null,"thumb":{"url":null},"large":{"url":null}},"invitation_accepted_at":null,"invitation_limit":null,"invitation_sent_at":null,"invitation_token":null,"invited_by_id":null,"invited_by_type":null,"last_name":"Tester","local_apt":"","local_city":"San Antonio","local_state":"Texas","local_street":"One UTSA Circle","local_zip":"78249","major":"Computer Science","permanent_apt":"","permanent_city":"","permanent_state":"","permanent_street":"One UTSA Circle","permanent_zip":"","phone":"5558813284","same_address":true,"tour_trained":false,"updated_at":"2012-08-17T03:35:26-05:00","utsa_id":"uoi431"},
{"banner":"","birthday":"1990-10-25","committee_id":null,"created_at":"2012-08-03T16:19:23-05:00","email":"you#example.com","first_name":"Test","graduation_date":null,"hometown":null,"hours_enrolled":null,"id":1,"image":{"url":null,"thumb":{"url":null},"large":{"url":null}},"invitation_accepted_at":null,"invitation_limit":null,"invitation_sent_at":null,"invitation_token":null,"invited_by_id":null,"invited_by_type":null,"last_name":"User","local_apt":"","local_city":"","local_state":"","local_street":"","local_zip":"","major":null,"permanent_apt":"","permanent_city":"","permanent_state":"","permanent_street":"","permanent_zip":"","phone":"","same_address":false,"tour_trained":false,"updated_at":"2012-08-15T10:05:54-05:00","utsa_id":""}]
Potential solution would be to go through each internal hash, determining value of relevant key value, then store, based on where the key value places it compared to already tested hashes. When complete, return.
Ok so if you have objects that are set up to parse this information, those objects can build themselves based off the parameters of your hash. So you could do something like this
object = MyObject.create(your_hash_parameters)
Where your_hash_parameters are the parameters that you presented in your example.
I'm not sure what would happen if there were more paramaters than your object knew what to do with, if it would still build itself or not. If that is the case, you could use the delete_if method to exclude attributes that are unwanted.
One more note, if this isn't something that you want saved to your database, and its only to display temporary information. I would set up a model with attr_accessors that represent the attributes that you are displaying.
As told in comment, I'd create an ActiveResource object and add relevant methods to it.

Resources