Ruby's `.present?` without Rails? - ruby

I'm developing a "Rails-less" Ruby daemon for automation (although in theory it runs within a Rails directory). For general purposes and the principle of the matter, I would like to find the (most) "native"/common way to utilize a Ruby version of .present?/.blank?/.empty?/.nil? to identify if an array or a (hash) value exists and is not empty (i.e., [] or {}).
From what I've read (e.g., Stack Overflow) and tested, all of these functions appear to be Rails-specific methods, part of ActiveSupport(?).
Coming from other web/interpreter languages (PHP, Python, JS, etc.), this is a general logic function most languages (with arrays, which are most) have this functionality built in one way or another (e.g., PHP's isset( ... ) or JavaScript's .length).
I understand there are RegEx workarounds for .blank?, but .present? seems it would require exception handling to identify if it's "present"). I'm having a hard time believing it doesn't exist, but there's little talk about Ruby without Rails' involvement.

Active Support is broken in small pieces so that you can load just what you need. For .blank? and .present? methods it would be enough to require:
require 'active_support/core_ext/object/blank.rb'
As docs say.
Object#nil? , Array#empty? and Hash#empty? already defined so you dont need anything to require to use those.
Make sure active_support gem installed in your system

You can use ActiveSupport without including all rails in your app, that's actually quite common.
nil? and empty? are defined in the standard library.
E.g., String#empty? is simply testing if the length is 0.
To use active support, just install the gem or add it to your gemfile then:
require 'active_support'
The documentation also states you can cherry pick the core extensions you want:
require 'active_support/core_ext/object/blank'

Related

How is the Ruby safe navigation (&.) implemented?

I was trying to figure out how the safe navigation operator is implemented but didn't find the source for it, would love to know how it works and how efficient it is.
The safe navigation operator was implemented following Feature #11537.
It is part of Ruby's core langiage, i.e. is implemented in the language parser, has an op code in the virtual machine. Thus, there is no single place where the operator is implemented. The first version of it was added in commit a356fe1c but it has seen multiple extensions since then.
As for how efficient it is, the answer is probably: quite. You might want to run your own benchmarks however to confirm whether it suits your requirements.
Before the safe navigation operator was implemented into the core language using C, there used to be a gem with similar functionality called andand. If you want to research how something like this could be implemented using Ruby, then the andand source is a good place to start:
https://github.com/raganwald/andand
require 'andand'
nil.andand.some_method
=> nil

How to have multiple gems that share the same common Ruby module?

I've written a Ruby module, common_services.rb, which contains convenience methods for interfacing with a web service; I consider it a piece of common code. Now, I would like to create two separate gems, both of which utilize the convenience methods in this module. I visualize something like this:
rubyStuff/
commonCode/
common_services.rb <-- common code lives here
gemA/
bin/
lib/ <-- gemA would like to pull in common_services to use it
gemA.gemspec
gemB/
bin/
lib/ <-- gemB would also like to pull in common_services to use it
gemB.gemspec
Each of gemA and gemB would have a reference to the common code in order to use it, for example rubyStuff/gemA/lib/gemA/main.rb might begin as:
require_relative '../../commonCode/common_services.rb'
puts CommonServices.getMessageOfTheDay()
<etc>
It's not working out too well for me, so I'm wondering if there is a better way to do this in Ruby. One problem I'm having is with packaging a gem to reference a file that is outside of its own path:
s.files = Dir['bin/**'] + Dir['lib/**/*'] + Dir['../commonCode/**']
When using the .. notation in the gemspec, and trying to install the resulting gem, produces:
ERROR: While executing gem ... (Gem::Package::PathError) installing into parent path /Users/me/.rvm/gems/ruby-2.0.0-p247/gems/commonCode/common_services.rb of /Users/me/.rvm/gems/ruby-2.0.0-p247/gems/gemA-0.0.1 is not allowed
It makes sense to me why gems are not allowed to reach outside of their own path, but I'm not sure how to resolve this issue. In Ruby, how and where should I organize Ruby code that will be used by multiple gems in my codeline, so that the multiple gems can use this common code? Am I going about reuse entirely the wrong way? Symbolic link magic?
Thanks for taking the time to read through this.
Summarizing comments above for posterity...
There are a couple things to consider here.
1. Is commonCode significant? Is it a good chunk of code, or just a few files?
2. Are gemA and gemB significant? Should each of them really be gems?
Seems like you're in either one of two situations, depending on the significance of the code you've written:
commonCode is significant enough (amount of code, complexity, logical separation from gemA and gemB) to merit its own gem? If so, definitely pull it out into its own gem. You can require gem-common in the other two. It doesn't make sense to require a plain ruby file in A and B that lives outside of those two code bases.
commonCode is too insignificant to be pulled into its own gem. If this is the case, you should consider whether or not gemA and gemB really deserve their own gems, each. If they aren't big enough or logically separate enough, maybe all three can be combined into a larger gem.

Advice on how/where to place requires in own gem

I am going through the blog Creating mountable Gem:
Its important to note that you should require your dependent gems explicitly in the root file of your gem. Say if your gem is named my_cool_gem, then you should have my_cool_gem.rb created inside lib folder. If your gem is dependent on strong_parameters, then you need to add these lines:
The author did not mention why it is required to have the dependent gems explicitly in the root file. Can some one explain why this needs to be done?
It's just cleaner. What if you had require statements in various files scattered all over your gem? It'd be a mess to easily see all the dependencies.
This statement:
Its important to note that you should require your dependent gems
explicitly in the root file of your gem.
It is not a strict statement that you have to conform to (to be fair to the author, the word is "should", not "must"). Some people prefer to take a different approach, and e.g. require dependencies only in parts of the library that use them.
However, you do need to consider:
Execution order of require statements that define symbols used elsewhere. You cannot call a DSL method that sets up instance methods for you, if the gem that provides the method has not yet been require-d
You should check that you really do require all correct the dependencies, and your gem functions correctly in projects that do not load them already.
With both of these in mind, it is often quickest and easiest to require dependencies early and and in a way that can be quickly viewed. So the advice is sound; as it was presented in a very short article, covering the statement with caveats and extra background would make the whole thing a lot less pithy.

Question about requiring files and the load path in Programming Ruby 1.9

I'm reading through "Programming Ruby 1.9". On page 208 (in a "Where to Put Tests" section), the book has the code organized as
roman
lib/
roman.rb
other files...
test/
test_roman.rb
other_tests...
other stuff
and asks how we get our test_roman.rb file to know about the roman.rb file.
It says that one option that doesn't work is to build the path into require statements in the test code:
# in test_roman.rb
require 'test/unit'
require '../lib/roman'
Instead, it says a better solution is for all other components of the application to assume that the top-level directory of the application is in Ruby's load path, so that the test code would have
# in test_roman.rb
require 'test/unit'
require '/lib/roman'
and we'd run the tests by calling ruby -I path/to/app path/to/app/test/test_roman.rb.
My question is: is this realy the best way? It seems like
If we simply replaced require '../lib/roman' in the first option with require_relative '../lib/roman', everything would work fine.
The assumption in the second option (that all components have the top-level directory in Ruby's load path) only works because we pass the -I path/to/app argument, which seems a little messy.
Am I correct that replacing require with require_relative fixes all the problems? Is there any reason to prefer the second option anyways?
Further on, that same book makes use of require_relative (Chapter 16, Organizing your source code) in the context of testing, so yes, I would say that using it is a Good Thing, since it "always loads files from a path relative to the directory of the file that invokes it".
Of course, like #christiangeek noticed, require_relative is new in the 1.9 series, but there's a gem that provides you with the same functionality.
It might be worth pointing out that the Pickaxe too provides a little method you can stick in your code in the same chapter I mentioned before.
require_relative does make the code cleaner but is only available natively on Ruby > 1.9.2. Which means if you want want your code to be portable to versions of Ruby < 1.9.2 you need to use a extension or the regular require AFAIK. The book is most likely a) written before 1.9.2 became widespread or b) providing a example for lowest common denominator.

What alternatives to IRB are there?

In the python world, there are a number of alternative python interpreters that add cool additional features. One particularly useful example is bpython, which adds dynamic syntax highlighting, automatically pulls documentation, and displays live autocomplete information. In the Ruby world, I have yet to uncover any projects which add to the basic IRB interpreter even a subset of these features. Am I just not looking hard enough, or is this just something the Ruby community is lacking?
Use Pry: https://github.com/pry/pry
Let's you:
start sessions at runtime
view method source code
view method documentation (not using RI so you dont have to pre-generate it)
pop in and out of different contexts
syntax highlighting
gist integration
view and replay history
open editors to edit method using edit-method obj.my_method syntax
A tonne more great and original features
What a coincidence. Rubyflow just yesterday announced the irbtools gem, which is a meta-gem containing lots of cool irb enhancement gems. It contains:
Colorized and output as comment by wirb and fancy_irb
Nice IRB prompt and IRB’s auto indention
Includes stdlib’s FileUtils: ls, cd, pwd, ln_s, rm, mkdir, touch, cat
Many debugging helpers: ap, q, o, c, y, Object#m, Object#d
ap – awesome_print
q – like p, but on one line
Object#m – ordered method list (takes integer parameter: level of nesting)
Object#d – puts the object, returns self (using tap)
“Magical” information constants: Info, OS, RubyVersion, RubyEngine
OS.windows?
RubyEngine.jruby?
RubyVersion.is.at_least? 1.9
Clipboard features: copy and paste
also available: copy_input and copy_output for session history
Call vim (or another supported editor) to edit a file, close it and it gets loaded into your current irb session, powered by interactive_editor
Another way of live loading into irb: sketches
Highlight a string with olorize('string') or a file with ray('path'), powered by coderay
Displays ActiveRecord database entries as tables with hirb
Restart irb with reset! or change the Ruby version with the use method and rvm!
Includes the current directory in the load path (was removed in 1.9.2 for security reasons, but is pretty annoying in IRB)
Shorter requiring like this: rq:mathn
And rerquiring with rrq
Try the included Object#ri helper, powered by ori!
Access to a lot of more commands with boson – call commands to get started
There are nice screenshots on the irbtools page. One nice thing about it is that each of the utilities can stand on its own, in case you just want to cherry-pick one or two features.
2013 Update
Since I wrote this, Pry has become a popular IRB replacement. It doesn't do as much as irbtools out of the box, but it extensible with plugin gems that add cool features. You can browse source code like it was a unix directory:
pry(main)> cd FileUtils
pry(FileUtils):1> show-method rm
From: /opt/ruby/lib/ruby/1.9.1/fileutils.rb # line 556:
Number of lines: 10
Owner: FileUtils
def rm(list, options = {})
fu_check_options options, OPT_TABLE['rm']
list = fu_list(list)
fu_output_message "rm#{options[:force] ? ' -f' : ''} #{list.join ' '}" if options[:verbose]
return if options[:noop]
list.each do |path|
remove_file path, options[:force]
end
end
pry(FileUtils):2>
You can also browse Ruby documentation, issue shell commands, and if you're a Rails user, you can use the pry-rails gem to get pry in your Rails console. There's also a way to hook it into Sinatra and use it with Heroku.
There's ample documentation--there are a bunch of screencasts including a Railscast. It's definitely worth looking into.
I've never heard of a (popular) alternative to IRB, but there certainly are several useful gems that make the IRB experience a lot nicer:
awesome_print pretty prints Ruby objects with indentation and coloring, very useful when trying to look at nested hashes or other complicated data structures.
looksee is pretty awesome too, it provides a method lp (lookup path) that shows you where a Ruby object gets its methods from (class, superclass etc).
Sketches connects your editor and IRB, so it's especially useful if you are the type who likes interactive development. Emacs with inf-ruby is also good for this.
Wirble is a whole set of IRB enhancements, like tab completion and syntax highlighting. There's also Utility Belt, but I don't personally use that, so can't comment on its features.
Edit
I forgot Hirb, which is very useful for e.g. showing the results of an ActiveRecord query in a Rails console.
There's http://github.com/alloy/dietrb.
JRuby ships with jirb_swing, which provides code completion.
There's not much in the area of alternatives to irb, but there are a couple of gems that add useful features to irb.
Most notably wirble, which, among other things, gives you colored output (not input though) and a history that goes beyond the current session.
Check out ripl, a modular irb alternative which is designed to be extendable. You may also get some answers from Is there something like bpython for Ruby?.
rib is a modular and light Ruby interactive shell.
It, like Pry, uses Ruby's parser so has consistent behavior with Ruby thus less bugs (e.g. https://stackoverflow.com/a/39271791/474597)
It is modular so one can easily extend it with more functionalities.
It is also still actively maintained as of 2016.
I made a pure Ruby console, inspired off Google Chrome's JavaScript console.
https://github.com/sancarn/RubyConsole
It's still mostly a WIP project as I keep finding bugs with the current algorithm, however I'm building it to be 1.9.3+ compatible.

Resources