• The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
Menu
  • The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
  • Ruby And DSLs And Blocks

    April 21, 2015 Aaron Bartell

    When I started with Ruby I was immediately drawn in by its syntax–simple, elegant, and easy to peruse. At the time I didn’t know this was an intentional mantra of the language put in place by Yukihiro “Matz” Matsumoto, Ruby’s creator. Matz said that he was “trying to make Ruby natural, not simple,” in a way that mirrors life. Further, Matz stated “Ruby is simple in appearance, but is very complex inside, just like our human body.” Let’s take this out of metaphor-land and into tangible code by introducing the DSL, or Domain Specific Language, aspect of Ruby.

    First, what is a Domain Specific Language (DSL)? Martin Fowler describes it as “. . . a computer language that’s targeted to a particular kind of problem, rather than a general purpose language that’s aimed at any kind of software problem.” DSLs have existed for decades and you’ve probably been using them without even knowing it. For example, jQuery is an example of a DSL because it uses the Javascript language to define easier ways to do things specific things, like make AJAX calls. The SQL syntax is also a DSL because it is giving you a higher-level syntax with which to query the database.

    In A Ruby and RPG Conversion we introduced the xmlservice Gem and provided the following callable RPG program and corresponding Ruby invocation code.

    --- MYLIB/PGM1 ---
     dcl-pr pgm1 extpgm; 
       char1 char(1);
       dec1 packed(7:4);
     end-pr;
     dcl-pi pgm1;
       char1 char(1);
       dec1 packed(7:4);
     end-pi;
    
     char1 = 'C';
     dec1 = 321.1234;
     return;
    
    
    pgm1 = XMLService::I_PGM.new("PGM1", 'MYLIB') <<
           XMLService::I_a.new('mychar1', 1, 'a') <<
           XMLService::I_p.new('mydec1', 7, 4, 11.1111) 
    pgm1.call
    

    One goal the xmlservice Gem team had was to create a DSL making it simpler and less verbose to make a call to programs. Looking at the above code we can see the “XMLService::” and “.new” text is repeated multiple times. What if we could get rid of that redundancy? We can. Below is a DSL to make program invocation simpler.

    Author’s Note: The xmlservice Gem is now jointly maintained by IBM and the KrengelTech Litmis open source team at bitbucket.org/litmis/xmlservice

    First we get an instance of the I_PGM Ruby object, which exists in the XMLService Ruby module. Next the DSL beauty comes into play when we invoke the input_parms method and pass in a Ruby block of the parameter definitions and initializing values.

    pgm1 = XMLService::I_PGM.new('PGM1','AARONLIB')
    pgm1.input_parms do
      char 'mychar1', 1, 'a'
      dec 'mydec1', 7, 4, 11.1111
    end
    

    What’s a Ruby block? In broader programming nomenclature it is a closure. Think of it as code that is sent to the method and invoked at a later point in time; in this case with what’s called the instance_eval method. Below is the input_parms method’s source code. Notice the &block being received into input_parms and subsequently used on the call to self.instance_eval. The instance_eval then evaluates the code and runs it in the context of itself, meaning, in this scenario, it looks for methods char and dec in this same Ruby program and invokes them.

     def input_parms(&block)
       @xml_isParm = true
       self.instance_eval(&block)
       self
     end
    

    Below is the char method definition from the xmlservice Gem. Notice how it still, in the end, invokes I_a.new as we saw in the original more verbose version of the Ruby code? This is how the DSL wrapped the more complex and verbose code to come up with the concise new syntax.

     def char(var, size, data=" ")
        el = I_a.new(var,size,data)
        if @xml_isParm
          self.inputParameter(nil,nil,el)
        else
          self.setReturn("xchr",el)
        end
        el
     end
    

    Ruby blocks and DSLs are used very frequently and in-favor over other language features. For example, the below shows a Ruby hash being iterated over using a Ruby DSL and block.

    my_hash = { one:   "value 1", 
                two:   "value 2", 
                three: "value 3"}
    
    my_hash.each do |key, value|
      puts "#{key} is #{value}"
    end
    

    The same iteration could have been accomplished using Ruby’s for statement.

    for key, value in my_hash
      puts "#{key} is #{value}"
    end
    

    When I bring up the topic Ruby blocks during speaking engagements I always tell people “don’t worry if you don’t yet understand how the innards work, just be a good imitator of someone else’s code and copy/paste”. Or said another way: don’t worry if you don’t understand how Ruby blocks work under the covers and instead understand how to be a user of them. Here and here are two more Ruby community references on how DSLs in Ruby work if you’d like more in-depth examples. Stay tuned for more articles on all-things open source!

    Aaron Bartell is Director of IBM i Innovation for Krengel Technology, Inc. Aaron facilitates adoption of open source technologies on IBM i through professional services, staff training, speaking engagements, and the authoring of best practices within industry publications and www.litmis.com. With a strong background in RPG application development, Aaron covers topics that enable IBM i shops to embrace today’s leading technologies including Ruby on Rails, Node.js, Git for RPG source change management and RSpec for unit testing RPG. Aaron is a passionate advocate of vibrant technology communities and the corresponding benefits available for today’s modern application developers. Connect with Aaron via email at abartell@krengeltech.com. Aaron lives with his wife and five children in Southern Minnesota. He enjoys the vast amounts of laughter having a young family brings, along with camping and music. He believes there’s no greater purpose than to give of our life and time to help others.

    RELATED STORIES

    IBM i Toolkit for Ruby, iit For Short

    RubyGems Are The Foundation Of Success

    A Ruby And RPG Conversation

    Git To GitHub

    Git To It

    Knee-Deep In Ruby Waters

    Testing The Ruby Waters

    Bash Is Not A Shell Game

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    Tags:

    Sponsored by
    DRV Tech

    Get More Out of Your IBM i

    With soaring costs, operational data is more critical than ever. IBM shops need faster, easier ways to distribute IBM applications-based data to users more efficiently, no matter where they are.

    The Problem:

    For Users, IBM Data Can Be Difficult to Get To

    IBM Applications generate reports as spooled files, originally designed to be printed. Often those reports are packed together with so much data it makes them difficult to read. Add to that hardcopy is a pain to distribute. User-friendly formats like Excel and PDF are better, offering sorting, searching, and easy portability but getting IBM reports into these formats can be tricky without the right tools.

    The Solution:

    IBM i Reports can easily be converted to easy to read and share formats like Excel and PDF and Delivered by Email

    Converting IBM i, iSeries, and AS400 reports into Excel and PDF is now a lot easier with SpoolFlex software by DRV Tech.  If you or your users are still doing this manually, think how much time is wasted dragging and reformatting to make a report readable. How much time would be saved if they were automatically formatted correctly and delivered to one or multiple recipients.

    SpoolFlex converts spooled files to Excel and PDF, automatically emailing them, and saving copies to network shared folders. SpoolFlex converts complex reports to Excel, removing unwanted headers, splitting large reports out for individual recipients, and delivering to users whether they are at the office or working from home.

    Watch our 2-minute video and see DRV’s powerful SpoolFlex software can solve your file conversion challenges.

    Watch Video

    DRV Tech

    www.drvtech.com

    866.378.3366

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    Sponsored Links

    Profound Logic Software:  Modernize 2015 @ COMMON. FREE Seminar. April 25, 8:30 a.m.
    BCD:  Free Webinar: Resolve PHP problems & optimize performance with Zend Server 8 & Z-Ray. April 21
    COMMON:  2015 Annual Meeting & Expo, April 26 - 29, at the Disneyland® Resort in Anaheim, California

    Observations From Oracle Collaborate 2015 The Remaining Power8 Systems Loom

    Leave a Reply Cancel reply

Volume 15, Number 08 -- April 21, 2015
THIS ISSUE SPONSORED BY:

WorksRight Software
CCSS
Storagepipe

Table of Contents

  • An SQL Pivot Procedure
  • Joining On Ranges
  • Ruby And DSLs And Blocks

Content archive

  • The Four Hundred
  • Four Hundred Stuff
  • Four Hundred Guru

Recent Posts

  • The Power11 Transistor Count Discrepancies Explained – Sort Of
  • Is Your IBM i HA/DR Actually Tested – Or Just Installed?
  • Big Blue Delivers IBM i Customer Requests In ACS Update
  • New DbToo SDK Hooks RPG And Db2 For i To External Services
  • IBM i PTF Guide, Volume 27, Number 33
  • Tool Aims To Streamline Git Integration For Old School IBM i Devs
  • IBM To Add Full System Replication And FlashCopy To PowerHA
  • Guru: Decoding Base64 ASCII
  • The Price Tweaking Continues For Power Systems
  • IBM i PTF Guide, Volume 27, Numbers 31 And 32

Subscribe

To get news from IT Jungle sent to your inbox every week, subscribe to our newsletter.

Pages

  • About Us
  • Contact
  • Contributors
  • Four Hundred Monitor
  • IBM i PTF Guide
  • Media Kit
  • Subscribe

Search

Copyright © 2025 IT Jungle