Posts

Showing posts with the label Ruby On Rails

Breaking Up Long Strings On Multiple Lines In Ruby Without Stripping Newlines

Answer : Maybe this is what you're looking for? string = "line #1"\ "line #2"\ "line #3" p string # => "line #1line #2line #3" You can use \ to indicate that any line of Ruby continues on the next line. This works with strings too: string = "this is a \ string that spans lines" puts string.inspect will output "this is a string that spans lines" Three years later, there is now a solution in Ruby 2.3: The squiggly heredoc. class Subscription def warning_message <<~HEREDOC Subscription expiring soon! Your free trial will expire in #{days_until_expiration} days. Please update your billing information. HEREDOC end end Blog post link: https://infinum.co/the-capsized-eight/articles/multiline-strings-ruby-2-3-0-the-squiggly-heredoc The indentation of the least-indented line will be removed from each line of the content.

ActiveModel Serializer - Passing Params To Serializers

Answer : AMS version: 0.10.6 Any options passed to render that are not reserved for the adapter are available in the serializer as instance_options . In your controller: def index @watchlists = Watchlist.belongs_to_user(current_user) render json: @watchlists, each_serializer: WatchlistOnlySerializer, currency: params[:currency] end Then you can access it in the serializer like so: def market_value # this is where I'm trying to pass the parameter Balance.watchlist_market_value(self.id, instance_options[:currency]) end Doc: Passing Arbitrary Options To A Serializer AMS version: 0.9.7 Unfortunately for this version of AMS, there is no clear way of sending parameters to the serializer. But you can hack this using any of the keywords like :scope (as Jagdeep said) or :context out of the following accessors: attr_accessor :object, :scope, :root, :meta_key, :meta, :key_format, :context, :polymorphic Though I would prefer :context over :scope for the p...

Bundle Install Returns "Could Not Locate Gemfile"

Answer : You just need to change directories to your app, THEN run bundle install :) You may also indicate the path to the gemfile in the same command e.g. BUNDLE_GEMFILE="MyProject/Gemfile.ios" bundle install I had this problem as well on an OSX machine. I discovered that rails was not installed... which surprised me as I thought OSX always came with Rails. To install rails sudo gem install rails to install jekyll I also needed sudo sudo gem install jekyll bundler cd ~/Sites jekyll new <foldername> cd <foldername> OR cd !$ (that is magic ;) bundle install bundle exec jekyll serve Then in your browser just go to http://127.0.0.1:4000/ and it really should be running

Bundler: You Must Use Bundler 2 Or Greater With This Lockfile

Answer : I had a similar experience. Here's how I solved it Display a list of all your local gems for the bundler gem gem list bundler N/B : The command above is for rbenv version manager, the one for rvm might be different This will display the versions of the bundler gem installed locally bundler (2.1.4, default: 1.17.2) if you don't have bundler version 2 installed locally, then run gem install bundler OR gem install bundler -v 2.1.4 if you have bundler version 2 already installed locally or just installed it, then you need to simply install an update for RubyGems Package Manager locally. To do this, run gem update --system And then finally run bundle update --bundler For Docker projects in Ruby on Rails If you're experiencing this issue when trying to build your application using Docker, simply do this: Delete the Gemfile.lock file Please don't create it again by running bundle install . Run your docker build or docker-compose build comm...

Bootstrap Shown.bs.tab Event Not Working

Answer : Bootstrap tab events are based off the .nav-tabs elements, not the .tab-content elements. So in order to tap into the show event, you need the element with an href that is pointed towards #tab1 , not the #tab1 content element itself. So instead of this: $('#tab1').on('shown.bs.tab', function (e) { console.log("tab1"); }); Do this instead: $('[href=#tab1]').on('shown.bs.tab', function (e) { console.log("tab1"); }); Or, to capture all of them, just do this: $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { console.log(e.target.href); }) Demo in Stack Snippets $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { console.log(e.target.href); }) <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/> <script src="//cdnjs.cloudflare.com/ajax/li...

Change Column Name Rails

Answer : Run in your console: $ rails g migration rename_season_to_season_id Now file db/migrate/TIMESTAMP_rename_season_to_season_id.rb contains following: class RenameSeasonToSeasonId < ActiveRecord::Migration def change end end Modify it as follows: class RenameSeasonToSeasonId < ActiveRecord::Migration def change rename_column :shoes, :season, :season_id end end Then run $ rake db:migrate in console. Either fix your migration and do rake db:rollback db:migrate or make another migration like so: rename_column :shoes, :season, :season_id if column_exists?(:shoes, :season) && !column_exists?(:shoes, :season_id) and then do rake db:migrate

ActionController::InvalidAuthenticityToken Rails 5 / Devise / Audited / PaperTrail Gem

Answer : As it turns out, Devise documentation is quite revealing with regard to this error: 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 . The fix was to change code in my application controller from this: protect_from_forgery with: :exception To this: protect_from_forgery prepend: true This issue did not manifest itself until I attempted adding Audited or Paper Trail gems.

Bundle Install Could Not Find Compatible Versions For Gem "bundler"

Answer : Alternatively, you can also remove bundler 2.x completely and only use Bundler 1.x: gem uninstall bundler -v ">= 2.0" gem install bundler -v "< 2.0" # Now you can use bundler as before bundle install Try to use gem install bundler -v 1.17.3 bundle _1.17.3_ install Your bundler gem is too big. You can downgrade for now by changing your gemfile to specify the lower version, and deleting the lock file again. gem 'bundler', '1.17.1' Then try these commands in the terminal gem install bundler -v 1.17.1 gem uninstall bundler -v 2.0.1 bundle update --bundler bundle install That last install command might be redundant. I'm on my phone so I can't test anything unfortunately. Best of luck! EDIT: This is now a Heroku issue. Got it. Heroku docs regarding Bundler Libraries The following libraries are used by the platform for managing and running >Ruby applications and cannot be specified. For application dependenc...

Bundle Install Is Not Working

Answer : Open the Gemfile and change first line from this source 'https://www.rubygems.org' to this source 'http://www.rubygems.org' remove the ' s ' from ' https '. As @Wasif mentioned, first make sure the Ruby Gems site is up and your network access is ok. If they works fine, try it like this: First, delete your Gemfile.lock file Then run gem update --system Then in your Gemfile try changing the first line source 'https://rubygems.org' to http:// (without an s ) Unless there is a problem with your connectivity this should fix the issue with bundle install .

Can't Update RubyGems

Answer : There is no need to take such drastic steps as completely rebuilding Ruby, reinstalling Rubygems from scratch or installing a version manager to solve this problem. There is simply a dependency cycle introduced by the release of hoe 2.3.0: rubygems-update 1.3.5 requires (among other things) hoe-seattlerb hoe-seattlerb requires hoe >= 2.3.0 hoe >= 2.3.0 requires rubygems >= 1.3.1 I wrote the blog post linked to by zipizap. To recap: If you've already tried to update, uninstall the latest rubygems-update first: sudo gem uninstall rubygems-update -v 1.3.5 Update to 1.3.0: sudo gem install rubygems-update -v 1.3.0 sudo update_rubygems Then update to latest: sudo gem update --system With the release of Rubygems 1.3.6, it looks like this problem may be gone. From the release notes: Development deps are no longer added to rubygems-update gem so older versions can update sucessfully. Oi - I feel your pain. I'll first ask the obvious; ...

Can You Get DB Username, Pw, Database Name In Rails?

Answer : From within rails you can create a configuration object and obtain the necessary information from it: config = Rails.configuration.database_configuration host = config[Rails.env]["host"] database = config[Rails.env]["database"] username = config[Rails.env]["username"] password = config[Rails.env]["password"] See the documentation for Rails::Configuration for details. This just uses YAML::load to load the configuration from the database configuration file ( database.yml ) which you can use yourself to get the information from outside the rails environment: require 'YAML' info = YAML::load(IO.read("database.yml")) print info["production"]["host"] print info["production"]["database"] ... Bryan's answer in the comment above deserves a little more exposure: >> Rails.configuration.database_configuration[Rails.env] => {"encoding"=>"unico...

Can I Use Font-awesome Icons On Emails

Answer : You can't use webfonts reliably in html emails. Some clients might respect and render them, but the majority don't. You can use this website to convert the icons into images, and then simply download the images and upload them to Imgur. From there you can use <img> tags to link to the Imgur images. Edit: A better solution would be to host the images on your own server with the same domain as your email's domain . This will increase the chance of images automatically being displayed on your emails, as they are normally hidden until the user decides to view them. For example, if I used myname@mydomain.com to send emails, I'd host the images on mydomain.com You can embed them as images in your email. You can use fa2png.io which converts the font awesome icons to png of required size as well as color.

Check If A Table Exists In Rails

Answer : In Rails 5 the API became explicit regarding tables/views, collectively data sources . # Tables and views ActiveRecord::Base.connection.data_sources ActiveRecord::Base.connection.data_source_exists? 'kittens' # Tables ActiveRecord::Base.connection.tables ActiveRecord::Base.connection.table_exists? 'kittens' # Views ActiveRecord::Base.connection.views ActiveRecord::Base.connection.view_exists? 'kittens' In Rails 2, 3 & 4 the API is about tables . # Listing of all tables and views ActiveRecord::Base.connection.tables # Checks for existence of kittens table/view (Kitten model) ActiveRecord::Base.connection.table_exists? 'kittens' Getting the status of migrations: # Tells you all migrations run ActiveRecord::Migrator.get_all_versions # Tells you the current schema version ActiveRecord::Migrator.current_version If you need more APIs for migrations or metadata see: ActiveRecord::SchemaMigration this is the ActiveRecord::Base...

Authenticate User Using Omniauth And Facebook For A Rails API?

Answer : the best way I found (after being stuck for a while on this issue ) is to do your omniauth2 (specifically in my case using satellizer angular plugin) manually... I'll discuss the solution for Facebook as it was my case, but everything could apply to any other provider. first you have to know how omniauth2 works (as documented for humans here)... Client: Open a popup window for user to authenticate. Client: Sign in (if necessary), then authorize the application. Client: After successful authorization, the popup is redirected back to your app. with the code (authorization code) query string parameter the redirect back url must match your front-end app url not the back-end url and it must be specified in your facebook app configurations Client: The code parameter is sent back to the parent window that opened the popup. Client: Parent window closes the popup and sends a POST request to backend/auth/facebook with code parameter. Server: code ( A...

Can I Print Debug Messages To The Browser Console In Ruby On Rails?

Answer : Simple. Just call puts 'your debug message' and it will be printed to where the server is logging. For instance, if you are running the rails server only by running rails s on a terminal, the output of puts will be on this same terminal. If you need more 'power' to debug, you should consider using IDE's like RubyMine to debug your code. Thus, you can place breakpoints and see all the application state. You can use console.log() in your views: #view.html.erb <script> console.log("Message"); </script> If you want to log in your Model, try: Rails.logger.debug "message!!"

Can I Pass Default Value To Rails Generate Migration?

Answer : You can't: https://guides.rubyonrails.org/active_record_migrations.html#column-modifiers null and default cannot be specified via command line. The only solution is to modify the migration after it's generated. It was the case in Rails 3, still the case in Rails 6 Rails migration generator does not handle default values, but after generation of migration file you should update migration file with following code add_column :users, :disabled, :boolean, default: false you can also see this link - http://api.rubyonrails.org/classes/ActiveRecord/Migration.html Default migration generator in Rails does not handle default values, there is no way around as of now to specify default value defined through terminal in rails migration. you would like to follow below steps in order to achieve what you want 1). Execute $ rails generate migration add_disabled_to_users disabled:boolean 2). Set the new column value to TRUE/FALSE by editing the new migration file cr...