The project is in a healthy, maintained state
Make methods similar to Javascript 's classnames available in the rails erb template.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
 Dependencies

Development

Runtime

>= 5.0, <= 6.1.4.4
 Project Readme

Classnames::Rails::View

This is a view helper that dynamically generates class attributes in Rails view, like JedWatson/classnames.

Usage

The Helper method is included automatically, so you can use it immediately.

<div class="<%= class_names('foo') %>">Hello World</div>
<%# <div class="foo">Hello World</div> %>

The class_names method takes any number of arguments which can be a string or hash. The argument 'foo' is short for { foo: true }. If the value associated with a given key is falsy, that key won't be included in the output.

class_names('foo', 'bar'); // => 'foo bar'
class_names('foo', { bar: true }); // => 'foo bar'
class_names({ 'foo-bar': true }); // => 'foo-bar'
class_names({ 'foo-bar': false }); // => ''
class_names({ foo: true }, { bar: true }); // => 'foo bar'
class_names({ foo: true, bar: true }); // => 'foo bar'

// lots of arguments of various types
class_names('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'

// other falsy values are just ignored
class_names(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'

Arrays will be recursively flattened as per the rules above:

var arr = ['b', { c: true, d: false }];
class_names('a', arr); // => 'a b c'

Change the method name

If you want to change the method name, you can change it with config when starting the application.

# config/application.rb
class Application < Rails::Application
  ...
  config.classnames_rails_view.method_name = :classes
end
<div class="<%= classes('foo') %>">Hello World</div>

Installation

Add this line to your application's Gemfile:

gem 'classnames-rails-view'

And then execute:

$ bundle

Contributing

  • The test uses Rspec. Please execute the test with rspec command.
  • Please code check with rubocop.

License

The gem is available as open source under the terms of the MIT License.