230 Matching Annotations
  1. Last 7 days
  2. Feb 2024
  3. Jan 2024
    1. Some frameworks call this “template inheritance”. In this example, we might say that the application layout “inherits from” or “extends” the base layout. In Rails, this is known as nested layouts, and it is a bit awkward to use. The standard Rails practice for nested layouts is complicated and involves these considerations
    2. But what if you want to reuse one layout within another?
  4. Dec 2023
  5. Nov 2023
    1. In this example, we still want app/models/shapes/circle.rb to define Circle, not Shapes::Circle. This may be your personal preference to keep things simple, and also avoids refactors in existing code bases. The collapsing feature of Zeitwerk allows us to do that:
    1. authenticate_by addresses the vulnerability by taking the same amount of time regardless of whether a user with a matching email is found: User.authenticate_by(email: "...", password: "...")
  6. Oct 2023
  7. Sep 2023
  8. Aug 2023
    1. I assume that the ActiveStorage::Attachment class gets reloaded dynamically and that the extensions are lost as they are only added during initialization. You’re correct. Use Rails.configuration.to_prepare to mix your module in after application boot and every time code is reloaded: Rails.configuration.to_prepare do ActiveStorage::Attachment.send :include, ::ActiveStorageAttachmentExtension end
  9. May 2023
  10. Mar 2023
  11. Feb 2023
    1. The reason is Rails only reads and creates the session object when it receives the request and writes it back to session store when request is complete and is about to be returned to user.
    2. Session race conditions are very common in Rails. Redis session store doesn't help either! The reason is Rails only reads and creates the session object when it receives the request and writes it back to session store when request is complete and is about to be returned to user.
    1. As you can see from the example, the session cookie is updated on every request, regardless of if the session was modified or not. Depending on when the response gets back to the client last, thats the cookie that will be used in the next call. For example, if in our previous example, if get_current_result’s response was slower than get_quiz, then our cookie would have the correct data and the next call to update_response would of work fine! So sometimes it will work and sometimes not all depending on the internet gods. This type of race condition is no fun to deal with. The implications of this is that using cookie storage for sessions when you are doing multiple ajax call is just not safe.
    2. A better solution would be to use a server side session store like active record or memcache. Doing so prevents the session data from being reliant on client side cookies. Session data no longer has to be passed between the client and the server which means no more potential race conditions when two ajax are simultaneously made!
  12. Jan 2023
  13. Dec 2022
    1. When configuring SMTP settings in an after_initialize block, the settings aren't picked up by ActionMailer. This leads to runtime errors, since ActionMailer tries the default settings.
  14. Nov 2022
  15. Sep 2022
  16. Jul 2022
    1. It really only takes one head scratching issue to suck up all the time it saves you over a year, and in my experience these head scratchers happen much more often than once a year. So in that sense it's not worth it, and the first time I run into an issue with it, I disable it completely.
    1. it should be normal for production apps to add authentication and authorization to their ActiveStorage controllers. Unfortunately, there are 2 possible ways to achieve it currently: Not drawing ActiveStorage routes and do everything by yourself Override/monkey patch ActiveStorage controllers None of them is ideal because in the end you can't benefit from Rails upgrades (bug fixes, etc) so the intention of this PR is to let people define a parent controller (inspired by Devise, maybe @carlosantoniodasilva can tell us his experience on this feature) so that people can add authentication and authorization in a single place and still benefit from the default controllers.
  17. Apr 2022
    1. The combined stuff is available to components using the page store as $page.stuff, providing a mechanism for pages to pass data 'upward' to layouts.

      bidirectional data flow ?! That's a game changer.

      analogue in Rails: content_for

      https://github.com/sveltejs/kit/pull/3252/files

    1. In Rails, this is known as nested layouts, and it is a bit awkward to use. The standard Rails practice for nested layouts is complicated and involves these considerations:
  18. Mar 2022
  19. Feb 2022
    1. As of Rails 7.0+, Active Record has an option for handling associations that would perform a join across multiple databases.

      impressive

    1. You can also use silence_redefinition_of_method if you need to define the replacement method yourself (because you're using delegate, for example).
    1. acts_as_tokened Quickly adds rails 5 has_secure_token to your model, along with some Post.find() enhancements to work with tokens instead of IDs.
    2. include Effective::CrudController
    3. # All queries and objects will be built with this scope resource_scope -> { current_user.posts } # Similar to above, with block syntax resource_scope do Post.active.where(user: current_user) end
  20. Jan 2022
    1. Rails 5 recently shipped, and among many other new features is a new renderer that makes it easy to render fully composed views outside of your controllers.
  21. Dec 2021
    1. How to Create a Micro-Job Marketplace Like Fiverr: Features, Cost, TimelineTimurTech JournalistMarketplaceProduct GuideHomeBlogEntrepreneurshipHow to Create a Micro-Job Marketplace Like Fiverr: Features, Cost, TimelinePublishedNov 19, 2021UpdatedNov 19, 202120 min readIt’s no secret that the COVID-19 pandemic has led many people to reconsider their jobs. Now, freelance as an alternative career path steadily becomes a reality. 50.9% of the U.S. workforce will be freelancing by 2027, a Statista survey shows. Businesses like Fiverr and fellow gig-focused companies rode the wave. To be more precise, they adopted a model allowing the hire of independent contractors without any legwork. How do such tools set the new trend in powering freelancers? In this article, we share proven methods geared towards freelance website growth. Moreover, you will get a glimpse of how to create a micro-job marketplace like Fiverr of your own.

      It’s no secret that the COVID-19 pandemic has led many people to reconsider their jobs. Now, freelance as an alternative career path steadily becomes a reality. 50.9% of the U.S. workforce will be freelancing by 2027, a Statista survey shows.

      Businesses like Fiverr and fellow gig-focused companies rode the wave. To be more precise, they adopted a model allowing the hire of independent contractors without any legwork. How do such tools set the new trend in powering freelancers?

      In this article, we share proven methods geared towards freelance website growth. Moreover, you will get a glimpse of how to create a micro-job marketplace like Fiverr of your own.

  22. Nov 2021
    1. How to Choose a Reliable SaaS Application Development CompanyKateCloud & SaaS Product ResearcherDmitryCEOSaaSHomeBlogEntrepreneurshipHow to Choose a Reliable SaaS Application Development CompanyPublishedAug 5, 2020UpdatedAug 5, 202012 min readCurrently, SaaS is the largest segment of the global public cloud services market. The growing SaaS industry provides an equal-opportunity atmosphere for businesses. It concerns enterprises from startups to tech giants – and any size in between. It explains why traditional software companies, like Microsoft and Adobe, decided to look into that direction too. Indeed, the time is ripe for developing a SaaS application now. But however tempting it may be, do not dive in headfirst with launching a SaaS product, because sometimes, it can be very challenging. That is why we have prepared a guide on finding a SaaS application development company that will be your best bet.

      Looking to build a SaaS app? You will need help of a reliable development team. Check our advice on how to choose a SaaS development company.

    1. SaaS Product Development: Why Choose Ruby on Rails Framework?KateCloud & SaaS Product ResearcherRuby/RailsSaaSHomeBlogTechnologySaaS Product Development: Why Choose Ruby on Rails Framework?PublishedSep 10, 2020UpdatedSep 10, 202013 min readWhich technology to pick for your SaaS business to succeed? This question is not uncommon in our days. In fact, quite the opposite because the SaaS model has become a meaningful part of every business domain. And the demand for SaaS product development is higher than ever and still increasing. This article will discuss the essential factors you need to consider when selecting a framework for your SaaS project. Also, we will introduce the top 3 frameworks for building a SaaS product with their pros and cons. Read on to see the best examples of SaaS applications.

      Choosing the right tech stack can help you save costs and make your app stand out in the saturated market. Let’s discuss why Ruby on Rails can be your best choice.

    1. What Makes Ruby on Rails Perfect for Marketplace Development?AlinaE-Commerce & SaaS StrategistMarketplaceRuby/RailsHomeBlogEntrepreneurshipWhat Makes Ruby on Rails Perfect for Marketplace Development?PublishedJul 13, 2020UpdatedJul 13, 202012 min readThe last several years have been marked with the rise of different marketplaces. Airbnb, AliExpress, Etsy, Booking.com are on everyone’s lips. That's not surprising that the idea of launching a second Amazon or eBay seems so appealing. To win the e-commerce race, entrepreneurs focus on providing excellent customer experience and build fast-loading and scalable websites. Besides, business owners take various security measures to protect their customers’ sensitive information. This way, they can gain clients’ trust and boost sales. When building a custom marketplace, what technology stack is best to achieve all these goals? Our answer is simple: Ruby on Rails. In this article, we will fill you in on the Ruby on Rails marketplace development. At Codica, we are passionate fans of this framework and have built numerous e-commerce platforms with its help. Based on our experience, we will discuss the key reasons to choose RoR for building a successful marketplace.

      The last several years have been marked with the rise of different marketplaces. Airbnb, AliExpress, Etsy, Booking.com are on everyone’s lips. That's not surprising that the idea of launching a second Amazon or eBay seems so appealing.

      To win the e-commerce race, entrepreneurs focus on providing excellent customer experience and build fast-loading and scalable websites. Besides, business owners take various security measures to protect their customers’ sensitive information. This way, they can gain clients’ trust and boost sales.

      When building a custom marketplace, what technology stack is best to achieve all these goals? Our answer is simple: Ruby on Rails.

      In this article, we will fill you in on the Ruby on Rails marketplace development. At Codica, we are passionate fans of this framework and have built numerous e-commerce platforms with its help. Based on our experience, we will discuss the key reasons to choose RoR for building a successful marketplace.

    1. 1) Order the one for your particular vehicle if you can otherwise the curvature of the side rails may not be correct which will dent the metal once secured.2) Look/feel under the headliner if you can prior to drilling into the roof, you may hit a beam which will be troublesome running a screw through multiple pieces of metal. You can also cut the side rails if necessary.3) Use non-corrosive silicone (does not smell like vinegar which will eventually eat away at the paint and rust) to seal up the holes that you drill into the roof. End caps doesn't appear to make a tight seal.4) Screws are stainless which are typically soft. Be careful not to overnighten! I actually used a rivnut/blind nut tool instead of just screws (About 25 bucks here on Amazon).
  23. Sep 2021
  24. Jul 2021
    1. Rails' inability to automatically route my link_to and form_for in STI subclasses to the superclass is a constant source of frustration to me. +1 for fixing this bug.

      I've had to work around this by doing record.as(BaseClass)

  25. Jun 2021
    1. As you can see Rails already adds error messages from associated models and doing it wrongly: Merging together errors from different models under same has_many association. :"employments.company"=>["can't be blank"] And this is wrong.
  26. Apr 2021
    1. class AuthConstraint def initialize(&block) @block = block || ->(_) { true } end def matches?(req) user = current_user(req) user.present? && @block.call(user) end def current_user(req) User.find_by_id(session[:user_id]) end end This is a flexible approach to defining route access based on any desired variable (roles, auth, etc...)

      Good solution, and might be needed if you want to base routes on roles, etc. — but this one is even easier if all you need is for it to be conditional based on signed in or not (because devise provides authenticated helper):

      https://hyp.is/lRq8tpNXEeuNn_9NxqJvdA/stackoverflow.com/questions/32407598/rails-4-devise-set-default-root-route-for-authenticated-users

    2. scope module: 'authenticated', constraints: AuthConstraint.new { |user| user.present? } do # Management dashboard root 'dashboards#index' end root 'home#index'
  27. Mar 2021
    1. Meh... as I said earlier, I think using Webpack is the recommended way now. Another issue is there is no way to generate source maps in production.
    2. But last I have seen comments from DHH, he considered webpack(er) recommended for JS, but Sprockets still the preferred solution for (S)CSS.
    3. I agree about lack of maintenance. It's probably because people use more and more Webpack.
    1. Run the complete unit with a certain input set, and test the side-effects. This differs to the Rails Way™ testing style, where smaller units of code, such as a specific validation or a callback, are tested in complete isolation. While that might look tempting and clean, it will create a test environment that is not identical to what happens in production.
    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.
  28. 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
  29. 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.

  30. Dec 2020
  31. Nov 2020
  32. Sep 2020
  33. 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.
  34. 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.
  35. Jun 2020
  36. May 2020
  37. 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:
  38. 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?
  39. 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:
  40. Dec 2019