Showing posts with label Ruby. Show all posts
Showing posts with label Ruby. Show all posts

Saturday, December 9, 2017

Clojure has lesser typing error problems than the others well-known dynamic typing languages

Give these snippets a try.
// JS
function foo () {
  bar(1)
}
# Ruby
def foo
  bar(1)
end
; Clojure
(defn foo [] 
  (bar 1))

As you can see from the images below, Clojure doesn't allow you to refer to an undeclared symbol. I believe this takes away quite a bit of typing error issues.

Sunday, July 10, 2016

Why I'm writing in Clojure and Ruby

Sandy Metz. Around the 35th minute of http://bikeshed.fm/70

I came from Smalltalk, and I segued to Java a little bit, hated every minute of it, and then fell saved by Ruby. And so I have spent the last 20 some years writing code in languages that had enormous faith in my ability to do the right thing. And along with that enormous faith in my ability to do the right thing, they gave me the freedom of everything.
...

(My summary: She talked to a guy after a conference who asked her how using dynamic language could possibly work, and she answered)

You just trust people. And he said they are not trustworthy. And I said well, they shouldn't write Ruby, they should write Java. I really prefer languages that allow me to shoot myself in the foot if I do but give me the power to do that.
-----

  • Has enormous faith in my ability to do the right thing
  • Give me the freedom of everything
  • You just trust people

These are exactly why I'm writing in Clojure and Ruby.

Friday, November 27, 2015

Terminal.app doesn't save history in El Capitan and you are using RVM

The cause is described here https://github.com/rvm/rvm/issues/3540#issue-113491283
The fix is here https://github.com/rvm/rvm/issues/3540#issuecomment-152824133

I copied the fix here just in case it's removed in the future

Another option is to create .bash_logout with a single line:

shell_session_update

Thursday, December 25, 2014

[Ruby] string to hex, hex to string

String to Hex

require 'digest'
Digest.hexencode(string)
string.unpack('H*').first
Hex to String

[hex].pack('H*')
Credit: http://stackoverflow.com/a/17223012 



Wednesday, August 27, 2014

Tuesday, January 28, 2014

Rails4's Active Record where not nil

Since Rails 4.0 no more .where('column_name IS NOT NULL'). Instead, we now can use
.where.not(column_name: nil)
Yay!

Monday, January 6, 2014

Solved a different cause of SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed (OpenSSL::SSL::SSLError)

You get SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed (OpenSSL::SSL::SSLError) or similar error when trying to request to a https endpoint but no any other people solutions you have found through googling seems to be able to fix it.

What I have found is that those blog posts and stackoverflow answers led me to the wrong direction. The problem is neither Ruby's false nor you misconfigured it. Instead, missing intermediate CA certificate is the cause of the problem.

To verify that you are having the same cause of problem that I had, try running these command and compare the results
$ ruby -rnet/http -e "puts Net::HTTP.get(URI('https://github.com'))"
$ ruby -rnet/http -e "puts Net::HTTP.get(URI('https://your_webserver'))"
If you get back proper result for the first command and get the same error for the second command. That's the same problem I had. If you get errors on both commands, this post won't help solving you problem.

What's happening is that Ruby doesn't have a certificate of the intermediate CA that is used to issue certificate of the server you are requesting to

Compare Certificate chain section of the result of these 2 commands
$ openssl s_client -connect github.com:443
$ openssl s_client -connect your_webserver.com:443
In github's server case, you will get 0 and 1. On the other hand, in your web server case, you probably get only 0. SSL certificate chains section of this nginx documentation page has a good explanation of the chain.

If you own that web server or has an access to it, go fix that and your ssl issue should be resolved. For nginx web server, the fix is described in the previous link.

Good luck.

Friday, October 4, 2013

Installing Ruby: cannot load such file -- [ openssl | zlib ]

If you like me, installed Ruby by compiling from source code manually, and found that this 2 errors when trying to install bundler

  • cannot load such file -- openssl
  • cannot load such file -- zlib
You missed configure make to compile with those 2 libraries. Follow these steps to fix this issue.
  1. Remove the installed Ruby with make clean
  2. Install libssl-dev with your OS's package manager of choice. E.g. apt-get install libssl-dev
  3. Install zlib1g-dev with your OS's package manager of choice. E.g. apt-get install zlib1g-dev
  4. Config make file to include openssl by go to ext/openssl and run ruby extconf.rb
  5. Config make file to include zlib by go to ext/zlib and run ruby extconf.rb
  6. Go back to ruby source code directory run make && make install
  7. You should be able to successfully run gem install bundler
You can also do the same thing for readline. Install libreadline-dev and run extconf.rb in ext/readline

Tested with ruby 2.0.0p247
Credit:

Monday, August 5, 2013

FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)

This error message from chef is not very useful
FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)
I took me a few hours to dig in to chef source code to figure out what's really happening. It turned out for me that chef doesn't like ~ (home) that I used in path declarations in the solo.rb file.

As I skimmed through the code, I have a feeling that any errors that occurs during fork process will cause this error message which does not explain anything. If your cause is not the same as me, unfortunately your only option is to go digging through chef source code. :(

Gem: Chef
Version: 11.6.0

Sunday, May 19, 2013

RubyMine can't find test_helper

I have been an RSpec user since I started working on Ruby and Rails. I usually run a spec file, which reflect the production code file that I'm currently working on, inside RubyMine. So far it has been working fine out of the box.

As a lot more people start talking about Minitest, I want to give it a try. I was starting a new project today. It was a perfect chance to try out Minitest. I expected it to work perfectly out of the box with RubyMine, but apparently it is not.

I got this error when I tried running my test as usual.
`require': cannot load such file -- test_helper (LoadError)
Basically, it says that Ruby can't find test_helper file that is required in the top of my Minitest test file. I knew that it's LOAD_PATH issue but I didn't actually know how to config it properly since I was spoiled by out of the box RSpec integration.

I did googling around by no luck. There's only a page show how to config Minitest report.

I did try to switch back to RSpec just to see whether it's still working fine, and it is. I looked at the runner command that's generated by RubyMine when we execute the spec. There's nothing special from what it generates for Minitest. It seems like RSpec does some work figuring out the path for us. That's why it works out of the box.

So I aim toward finding a way to manually config properly the test running path. Finally, I figured it out with the clue from this comment.

  • First go to Run > Edit Configurations.
  • On the left panel, select Defaults and Ruby
  • Put the absolute path to your Rails project into Working directory: field
  • Append field Ruby arguments with -Itest (tell Ruby to look into test directory)
  • If you had run the test before, you need to remove all the configurations under Ruby section (outside Defaults) to force them to load the new configuration
  • And enjoy the Minitest experiences! (Should work with TestUnit too)
There's one potential problem with this solution. If you do run any non-test Ruby files, they will always load test directory which you don't want them to. Personally I've never do that so this setup is fine for me.

Saturday, May 11, 2013

[Ruby] Run multiple MiniTest files in command line without other setup required (Rake, ...)

MiniTest is a great, simple build-in test framework for Ruby. We can use immediately without anymore setup beside installing Ruby. But there's an annoying limitation when starting a project that we can only run one file at a time via command line. Try to execute many files with "ruby *" doesn't help.

Here's the simplest way to run multiple minitest files I can think of
ruby -e "Dir.glob('**/*_spec.rb').each { |f| require File.expand_path(f) }"
Change suffix _spec to _test for test-unit style file.

Wednesday, May 1, 2013

[Blog] Great use of Null Object pattern

Last weekend, I watched a talk Code Smells: Your Refactoring Cheat Codes by John Pignata from MountainWest RubyConf 2013. I was really enjoyed with it. One of the technique that I really like is his use of Null Object pattern. Even though, I know this pattern for long time, but in the situation he was in, I would not be able to come up with the solution like that.

Almost at the end of the talk, his code came to the state that he has jobs and PushDaemon that pushing jobs to the worker. Because a job returned from factory can be nil, he needs to check and allow only non-nil job to be pushed. This is a well-known use case for Null Object Pattern. He modified factory to  return NullJob instead of nil. Now his PushDaemon doesn't need to check for nil anymore.

The code was cleaner without nil checking but pushing null job to worker is not so efficient. How can we avoid pushing NullJob to the worker without checking for nil? That was the time he showed a great technique. Flipping push method (<<) in PushDaemon which was send to worker list to send to job with the opposite direction (>>) and pass worker list as an argument instead. Then implements >> for all the jobs to push itself to worker list except for NullJob. >> of NullJob does nothing. At the end, everything fall cleanly and efficiently.

I highly recommend you to check out his talk for other great refactoring techniques yourself from the link beginning of this blog or on his blog directly.

Thursday, April 18, 2013

[RSpec] Refer to let value that has the same name in outer scope

There is a situation in RSpec when you want to redefine let value in the inner scope base on value from the outer scope. In RSpec 2.13, you can do that by referring outer scope value with super() (parens are required)

Credit: RSpec 2.13 is released!

Thursday, February 21, 2013

Execute one line command on IRB or Rails's console through Unix shell

Basic Unix approach - echo and pipe:
$ echo "<command>" | irb
For example,
$ echo "1 + 1" | irb
1 + 1
2
You can change irb to rails console to execute that command in the Rails environment.

Thursday, February 7, 2013

Allow other people to publish gem to RubyGems

To do that, you need to add them as an owner of that gem with gem owner command.

This is an example
gem owner gem_name -a foo@bar.com
Credit: How to add more 'owners' to a gem in RubyGem

Thursday, January 31, 2013

Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

I ran to this issue couples of week ago
Installing oj (2.0.2) with native extensions 
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

        /Users/viki/.rvm/rubies/ruby-1.9.3-p194/bin/ruby extconf.rb 
>>>>> Creating Makefile for ruby version 1.9.3 on x86_64-darwin11.4.0 <<<<<
creating Makefile

make
compiling cache.c
compiling cache8.c
compiling dump.c
compiling fast.c
compiling load.c
compiling oj.c
compiling saj.c
clang: error: unable to execute command: Segmentation fault: 11
clang: error: clang frontend command failed due to signal 2 (use -v to see invocation)
clang: note: diagnostic msg: Please submit a bug report to http://developer.apple.com/bugreporter/ and include command line arguments and all diagnostic information.
clang: note: diagnostic msg: Preprocessed source(s) and associated run script(s) are located at:
clang: note: diagnostic msg: /var/folders/qw/xj8ns4cn09jfv1x5qq1mhn7m0000gn/T/saj-4CFmfe.i
clang: note: diagnostic msg: /var/folders/qw/xj8ns4cn09jfv1x5qq1mhn7m0000gn/T/saj-4CFmfe.sh
make: *** [saj.o] Error 254


Gem files will remain installed in /Users/viki/.rvm/gems/ruby-1.9.3-p194@raynor/gems/oj-2.0.2 for inspection.
Results logged to /Users/viki/.rvm/gems/ruby-1.9.3-p194@raynor/gems/oj-2.0.2/ext/oj/gem_make.out

I could find the way to fix it. It was quite frustrated at that moment because the only way to get passed this error to start our web server again is to downgrade oj gem.

But eventually, I found the way to fix it. As I understand, this error causes by bug in llvm (Apple's gcc that comes with XCode). Here is the steps of how I fixed the issue.

First you need to install gcc4.2 with brew

brew update
brew tap homebrew/dupes
brew install apple-gcc42
Then reinstall your Ruby with this command (I use RVM)

CC=/usr/local/Cellar/apple-gcc42/4.2.1-5666.3/bin/gcc-4.2 rvm install 1.9.3-pXXX
After this you should be able to install oj or the other gems as usual.

I composed solution from many links but sorry I forgot to take note of those.



Saturday, July 14, 2012

Never ending function

Today, I had a Clojure quiz for myself. How to write a function that print out a number and return a function that will print out an incremented number and return out a function with the same behavior again and again, never end.

For those who are familiar with Clojure might find it easy but for me it took a while and I couldn't solve it so I decided to start solving it with Ruby first.

This is my solution.
After that it was way more easier to port it to Clojure.

Tuesday, June 26, 2012

Curry in Ruby

While I was wandering around Proc and Lambda in Ruby, I found very useful method Proc#curry. This method answer the question that bugs me for a while, is there an easy way to make Curry happen in Ruby? Let look at the example how to use it.


Start with a simple method: Manually currying: But with Proc#curry, you can heavily simplify your code like this: Pretty neat!

Monday, May 14, 2012

Things I Didn't Know Rails Could Do

Something I thing it's easy and useful to me from James Edward Gray II presentation in RailsConf 2012
Ten Things You Didn't Know Rails Could Do


  • rails c --sandbox
  • rake db:migrate:status
  • pluck
    • User.pluck(:email)
    • User.uniq.pluck(:email)
  • Count Record in Group
    • Model.group(:column).count
  • File.atomic_write
  • { nested: { a: 1 } }.deep_merge(nested: { b: 2 })
  • hash.except(:key1, :key2)
  • hash1.reverse_merge(hash2) # keep hash1 value if hash2 has a duplicate key
  • content_tag_for(:tag, array) { |e| # content_inside }
  • render partial: @active_record_model & to_partial_path
  • grouped_options_for_select

Collectd PostgreSQL Plugin

I couldn't find this link when searching with google https://www.collectd.org/documentation/manpages/collectd.conf.html#plugin-postgresq...