125 Matching Annotations
  1. Last 7 days
    1. Responders don't use valid? to check for errors in models to figure out if the request was successful or not, and relies on your controllers to call save or create to trigger the validations.
  2. Feb 2021
    1. While Trailblazer offers you abstraction layers for all aspects of Ruby On Rails, it does not missionize you. Wherever you want, you may fall back to the "Rails Way" with fat models, monolithic controllers, global helpers, etc. This is not a bad thing, but allows you to step-wise introduce Trailblazer's encapsulation in your app without having to rewrite it.
    1. By default, hashes remove any keys that aren't given as nested filters. To allow all hash keys, set strip: false. In general we don't recommend doing this, but it's sometimes necessary.
    2. ActiveInteraction type checks your inputs. Often you'll want more than that. For instance, you may want an input to be a string with at least one non-whitespace character. Instead of writing your own validation for that, you can use validations from ActiveModel. These validations aren't provided by ActiveInteraction. They're from ActiveModel. You can also use any custom validations you wrote yourself in your interactions.
    3. Since we're using an interaction, we don't need strong parameters. The interaction will ignore any inputs that weren't defined by filters. So you can forget about params.require and params.permit because interactions handle that for you.
    4. Note that it's perfectly fine to add errors during execution. Not all errors have to come from type checking or validation.
    1. with ActiveForm-Rails, validations is the responsability of the form and not of the models. There is no need to synchronize errors from the form to the models and vice versa.

      But if you intend to save to a model after the form validates, then you can't escape the models' validations:

      either you check that the models pass their own validations ahead of time (like I want to do, and I think @mattheworiordan was wanting to do), or you have to accept that one of the following outcomes is possible/inevitable if the models' own validations fail:

      1. if you use object.save then it may silently fail to save
      2. if you use object.save then it will fail to save and raise an error

      Are either of those outcomes acceptable to you? To me, they seem not to be. Hence we must also check for / handle the models' validations. Hence we need a way to aggregate errors from both the form object (context-specific validations) and from the models (unconditional/invariant validations that should always be checked by the model), and present them to the user.

      What do you guys find to be the best way to accomplish that?

      I am interested to know what best practices you use / still use today after all these years. I keep finding myself running into this same problem/need, which is how I ended up looking for what the current options are for form objects today...

    2. I agre with your concern. I realy prefer to do this : form.assign_attributes(hash) if form.valid? my_service.update(form) #render something else #render somthing else end It looks more like a normal controller.
    3. My only concern with this approach is that if someone calls #valid? on the form object afterwards, it would under the hood currently delete the existing errors on the form object and revalidate. The could have unexpected side effects where the errors added by the models passed in or the service called will be lost.
    4. My concern with this approach is still that it's somewhat brittle with the current implementation of valid? because whilst valid? appears to be a predicate and should have no side effects, this is not the case and could remove the errors applied by one of the steps above.
    1. By explicitly defining the form layout using ::property there is no more need for protecting from unwanted input. strong_parameter or attr_accessible become obsolete. Reform will simply ignore undefined incoming parameters.
    1. Any attribute in the list will be allowed, and any defined as attr_{accessor,reader,writer} will not be populated when passed in as params. This means we no longer need to use strong_params in the controllers because the form has a clear definition of what it expects and protects us by design.

      strong params not needed since form object handles that responsibility.

      That's the same opinion Nick took in Reform...

    1. @conference_form.submit(conference_params)

      Surprised they called it submit, since that could imply that you're triggering an action called submit.

      They use other verbs to describe this:

      • sync
      • populate
      • write

      Analogous to Reform's sync / sync_models method.

      Actually, the name makes a lot of sense when you see it in context:

          @conference_form = ConferenceForm.new(conference)
          @conference_form.submit(conference_params)
      
          if @conference_form.save
      
    1. If you include ActiveModel::Validations you can write the same validators as you would with ActiveRecord. However, in this case, our form is just a collection of Contact objects, which are ActiveRecord and have their own validations. When I save the ContactListForm, it attempts to save all the contacts. In doing so, each contact has its error_messages available.
    2. Of course our object doesn't have any contacts yet, so our controller will need to make sure that the form has at least one fields_for block to render by giving it one on initialization
  3. Jan 2021
    1. config.action_mailer.register_preview_interceptor :css_inline_styler

      That's probably the same hook that https://github.com/fphilipe/premailer-rails ties into, for it says:

      Emails are only processed upon delivery, i.e. when calling #deliver on the email, or when previewing them in rails.

  4. Dec 2020
  5. Nov 2020
  6. Sep 2020
  7. Aug 2020
    1. Ruby is the programming language used in Translation Proxy. For Sarah, Object Oriented Design “done the Ruby way” is so enjoyable and is the part of her work that she likes most.
  8. Jul 2020
    1. RAILS_ENV determines which Webpacker YAML settings are used and NODE_ENV determines which webpack configuration is used.
    2. This finally brings us to the use case for NODE_ENV=test: JavaScript unit testing By this I mean executing tests, written in JavaScript, against your application JavaScript code within a Node.js process.
    1. You can also just throw<% yield :javascript_packs %>somewhere in your layout, and use<%= content_for :javascript_packs do %><%= javascript_pack_tag 'visitor' %><% end %>
    1. Why did Rails team decide they need to implement their own "version" of Timecop?

      On the one hand, that's great to reduce dependencies, but on the other hand, small dependencies are great (and rails already has lots of them), it just bloats ActiveSupport more, and creates a needless "duplication" of an already popular de facto standard for this problem -- one which (unlike Timecop) can't be easily used outside of the Rails/ActiveSupport ecosystem. It doesn't seem different enough to warrant creating it...

      Timecop: Works with Rails and non-Rails

      ActiveSupport::Testing::TimeHelpers: for use outside rails, requires dependency on bigger gem, AS.

    1. (Note that you rarely want to deal with Time.now, or Date.today, in order to honor the application time zone please always use Time.current and Date.current.)
    1. The best way to do this is create a new Rails environment, profile.rb.
    1. Actually, thats the one thing I’ve always thought Middleman got better than Rails: instead of eg, calling ‘render :admin’ in the general layout, you would ‘wrap_layout :application’ inside the specific (admin) one. It’s much more ergonomic this way.
  9. Jun 2020
  10. May 2020
  11. Apr 2020
    1. As mentioned in StateMachines::Machine#state, you can define behaviors, like validations, that only execute for certain states. One important caveat here is that, due to a constraint in ActiveRecord's validation framework, custom validators will not work as expected when defined to run in multiple states.
    1. For Rails 5, note that protect_from_forgery is no longer prepended to the before_action chain, so if you have set authenticate_user before protect_from_forgery, your request will result in "Can't verify CSRF token authenticity." To resolve this, either change the order in which you call them, or use protect_from_forgery prepend: true.
    1. Rails also adds a test method that takes a test name and a block. It generates a normal Minitest::Unit test with method names prefixed with test_. So you don't have to worry about naming the methods, and you can write something like:

      Or you could use the "it" format mentioned on https://devhints.io/minitest.

      Or better yet, just use rspec...

    1. The translated model name, translated attribute name, and value are always available for interpolation as model, attribute and value respectively.
    1. There are few ways to build forms with objects that don't inherit from Active Record, as follows:
  12. Mar 2020
    1. If you ever need to work with external translators, it’s a bit of a pain sending both your YML files and a bunch of views like index.en.html.erb. For one thing, you need some code to find all those files and send them, and put them back after receiving the translations. For another, your translator must respect the markup and code of the template, and know not to translate them. And if you want to use tools like WebTranslateIt, it’s easier to stick to YML.

      Good point. Better to store translations in your I18n backend in the same place as your subject translations, etc. (which by default is in YAML file).

    1. Action View has the ability to render different templates depending on the current locale.For example, suppose you have an ArticlesController with a show action. By default, calling this action will render app/views/articles/show.html.erb. But if you set I18n.locale = :de, then app/views/articles/show.de.html.erb will be rendered instead. If the localized template isn't present, the undecorated version will be used. This means you're not required to provide localized views for all cases, but they will be preferred and used if available.

      This is one option, but there is another camp that says it's better to store translations in your I18n backend in the same place as your subject translations, etc.: https://thepugautomatic.com/2012/07/rails-i18n-tips/

    1. ActionController and ActionMailer default include AbstractController::Rendering directly or indirectly (ActionController::Metal::Rendering). AbstractController::Rendering uses ActionView as default library for its template rendering engine and includes AbstractController::ViewPaths and an instance of I18n proxy to find localized views. To learn more i'd like to refer to the ActionPack source code on github. To get to the point. ActionView allows you to use localisation in your templates: See Rails guide: Action View Overview , Chapter Localized views.

      Not a very detailed or good code dissection, but is kind of one.

    1. For several reasons the Simple backend shipped with Active Support only does the "simplest thing that could possibly work" for Ruby on Rails3 ... which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but cannot dynamically store them to any format.That does not mean you're stuck with these limitations, though. The Ruby I18n gem makes it very easy to exchange the Simple backend implementation with something else that fits better for your needs, by passing a backend instance to the I18n.backend= setter.
    1. it comes down to opportunities for code reuse. Will your system re-use more code if you use WordPress and its very usable admin area, myriad of available plugins and themes? Or can you re-use more code by harnessing the object-oriented design, DSLs and good software development practices mecca that is Ruby, Rails and the available libraries and tools?
  13. Feb 2020
    1. The :shallow_prefix option adds the specified parameter to the named route helpers:
    2. You can also specify the :shallow option in the parent resource, in which case all of the nested resources will be shallow:
    3. The shallow method of the DSL creates a scope inside of which every nesting is shallow. This generates the same routes as the previous example:
  14. Dec 2019
    1. If you need more advanced React-integration, like server rendering, redux, or react-router, see shakacode/react_on_rails, react-rails, and webpacker-react.
    1. This gem also includes a responders controller generator, so your scaffold can be customized to use respond_with instead of default respond_to blocks. From 2.1, you need to explicitly opt-in to use this generator by adding the following to your config/application.rb: config.app_generators.scaffold_controller :responders_controller
    2. Responders don't use valid? to check for errors in models to figure out if the request was successful or not, and relies on your controllers to call save or create to trigger the validations.
    1. Arguably, the rails-team's choice of raising ArgumentError instead of validation error is correct in the sense that we have full control over what options a user can select from a radio buttons group, or can select over a select field, so if a programmer happens to add a new radio button that has a typo for its value, then it is good to raise an error as it is an application error, and not a user error. However, for APIs, this will not work because we do not have any control anymore on what values get sent to the server.
    2. liberal_enum :kind
    1. When the controller creates the user, instead of adding a validation error to the record, it raises an exception. How to avoid this?
    2. I really dislike the reasoning as stated in the issue listed above. Since the value is coming over the wire, it should be treated the same as a freetext input where the expectation is to validate in the model and not the controller. This is especially true in APIs where the developers have even less of a say as far as expected input coming from form data (for example).
    3. In case anyone wants a hack, here is what I came up with.
  15. Nov 2019
  16. Sep 2019
  17. Aug 2019
  18. Jun 2019
    1. At each stage of developing the sample application, we will write small, bite-sized pieces of code—simple enough to understand, yet novel enough to be challenging. The cumulative effect will be a deeper, more flexible knowledge of Rails, giving you a good background for writing nearly any type of web application.
    2. Following the scaffolding approach risks turning you into a virtuoso script generator with little (and brittle) actual knowledge of Rails.
  19. Nov 2016
    1. "American Idiot" - Green Day

      Green Day's first number one album since 1994's multi-platinum Dookie--which is likely due to the fact that while the lyrics may have a deeper meaning, the hooks are still there, and they are played with the same intensity that made the group famous more than a decade ago. Spin said the title track was "Green Day's most epic song yet.

    2. Now everybody do the propaganda,And sing along to the age of paranoia.

      The work challenges listeners to dig deeper than the high-octane guitars and thundering drums that drive the record's jubilant pop sheen. This is a multi-layered, literate narrative that effectively wields anger, wit, and bombast to expose the ugliness that seeps below the surface of this country's patriotism, commercialism, and nationalism.

    3. We're not the ones who're meant to follow.

      "A lot of rock music lacks ambition. Rock has become stagnant. There are a lot of bands that aren't doing anything differently than what's currently going on in pop music--like issuing a single, putting out a record, making a video, and hopefully getting on a tour with a bigger band. I think the reason hip-hop has become so much bigger than rock lately is because those artists are much more ambitious, and they are making records that have a concept and characters. They sound like a script." ~Billy Joe Armstrong

    4. Television dreams of tomorrow.

      "All my songwriting is about creating a statement and taking action. On American Idiot, it's reflecting on what's going on in the world right now." ~Billy Joe Armstrong

  20. Jan 2016
    1. require 'active_record/connection_adapters/postgis_adapter/railtie'

      The following worked better in my setup:

      require 'active_record/connection_adapters/postgis/railtie'