Home > database >  What does rails DSL configuration mean and what does a DSL configuration look like?
What does rails DSL configuration mean and what does a DSL configuration look like?

Time:07-17

So i have the following bower file :-

group :vendor, assets_path: 'assets/shop' do
  asset 'jquery', '2.2.1'
  asset 'lodash', '4.6.1'
  ...
end

Now i see the output in the folder vendor/assets/shop, which is as per what is specified in the docs HERE.

What i'am trying to understand is what does rails DSL configuration really mean ? and what does a rails DSL configuration or even DSL configuration look like ? I looked around and really could't find a definition to what exactly this statement means. Would appreciate if somebody could shed some light on this please.

CodePudding user response:

DSL is Domain Specific Language. "Domain Specific" here meaning the language is for a very particular use, in this case it is only for configuring Bower. In contrast, a General Purpose Language like Ruby or JSON can be used for anything.

DSLs are used to make writing code or configurations more natural and convenient and less error prone for humans in that domain. It makes it more declarative, fills in defaults, and constrains you to what you need for the domain.

This is a Bower DSL configuration.

resolution "angular", "1.2.22"

It is equivalent to this JSON configuration.

{
  "name" : "dsl-generated-dependencies",
  "dependencies": {
    "angular": "1.2.22"
  },
  "resolutions": {
    "angular": "1.2.22"
  }
}

Bower offers both options for configuration. You can use the DSL to generate the JSON config, or you can write the JSON by hand.


While sometimes DSLs are their own complete languages with their own grammar and parser, in Ruby DSLs are usually just Ruby. resolution "angular", "1.2.22" is just a method call: self.resolution("angular", "1.2.22"). resolution knows how to turn that into complete Bower configuration.

Your example code is a method call to group passing in a Proc.

self.group(:vendor, assets_path: 'assets/shop') do
  self.asset('jquery', '2.2.1')
  self.asset('lodash', '4.6.1')
  ...
end

Other examples of Ruby DSLs include config/routes.rb in Rails,

get '/patients/:id', to: 'patients#show', as: 'patient'

Gemfiles,

gem "nokogiri", ">= 1.4.2"

And FactoryBot.

factory :user do
  first_name { "John" }
  last_name  { "Doe" }
  admin { false }
end

They're all fancy Ruby method calls and blocks.

  • Related