Refinements in Ruby: in map: super: no superclass method

I was trying out refinements to see if they would help clean up some parsing code. I liked defining a couple of methods for the String class to respond to, but really didn't want them as permanent monkey patches on String.

And so, I had a pipe mapping module with refinements:

module PipeMapping
  refine String do
    def only_lines_with_pipes
      self.lines.select { |s| s =~ /\|/ }
    end
    def pipes_to_array
      self.split('|').map(&:strip)
    end
  end
end

I added the following to my class to allow it to load itself:

  using PipeMapping
  def self.initalize_mappings
    data_to_load.only_lines_with_pipes.map(&:pipes_to_array).each do |mapping|
      # do stuff
    end
  end

I got the following output:

...in `map': super: no superclass method `pipes_to_array' for "A|B|C\n":String (NoMethodError)

The problem is that Symbol#to_proc will end up operating outside of the scope of the refinement using invocation, and will, therefore, have no knowledge of the method.

A quick change to a block works:

  using PipeMapping
  def self.initalize_mappings
    data_to_load.only_lines_with_pipes.map{|s| s.pipes_to_array}.each do |mapping|
      # do stuff
    end
  end

I'm still trying to decide if this is a satisfactory trade-off.

rails (4) generate migration behaviors I forget to use

When I'm generating a migration, I usually don't go any deeper than specifying column_name:data_type on the command line, and often I only use the command line to generate the file itself.

I don't know that the other options really save all that much typing, but stopping to think about the other options for a few seconds might just help avoid having to go back later and add things.

Elementary things I don't make enough use of:

  • rails g migration AddXXXtoYYY automatically creates an add_column for table YYY for every column name specified.
  • rails g migration RemoveXXXtoYYY automatically creates a remove_column for table YYY for every column name specified.
  • Specifying column_name:data_type:index also adds an index to the new column.
  • rails g migration CreateJoinTableXXXYYY will produce a join table.

Applescripts to Mute or Unmute Lync

In preparation for hooking up Lync muting and unmuting to separate hotkeys, I wanted to make sure that my scripts no longer toggled the mute button, but only muted or unmuted.

For that to work, I needed to retrieve the current state of the checkbox.

set theCheckbox to checkbox 5 of splitter group 1 of aWindow
tell theCheckbox
  set checkboxStatus to value of theCheckbox as boolean
  if checkboxStatus is true then click theCheckbox
end tell

In this case, I store off the checkbox into a variable theCheckbox and then later the checkbox status into a variable, allowing me to unset the checkbox if it is true.

This results in the following script for unmuting:

tell application "Microsoft Lync"
	activate
end tell
tell application "System Events"
	tell process "Microsoft Lync"
		repeat with aWindow in (get every window)
			set aName to get the name of aWindow
			set initialName to ((characters 1 through 12 of aName) as string)
			if (initialName = "Conversation") then
				activate aWindow
				set theCheckbox to checkbox 5 of splitter group 1 of aWindow
				tell theCheckbox
					set checkboxStatus to value of theCheckbox as boolean
					if checkboxStatus is true then click theCheckbox
				end tell
			end if
		end repeat
	end tell
end tell

And for muting:

tell application "Microsoft Lync"
	activate
end tell
tell application "System Events"
	tell process "Microsoft Lync"
		repeat with aWindow in (get every window)
			set aName to get the name of aWindow
			set initialName to ((characters 1 through 12 of aName) as string)
			if (initialName = "Conversation") then
				activate aWindow
				set theCheckbox to checkbox 5 of splitter group 1 of aWindow
				tell theCheckbox
					set checkboxStatus to value of theCheckbox as boolean
					if checkboxStatus is false then click theCheckbox
				end tell
			end if
		end repeat
	end tell
end tell

These scripts (and hopefully, others soon) are available on GitHub

Toggling the mute button in Microsoft Lync for Mac via Applescript

Through liberal use of the dictionary for Microsoft Lync, the Accessibility Inspector, and a few web links, I've come up with this script which toggles the mute button in Lync for Mac.

tell application "Microsoft Lync"
  activate
end tell
tell application "System Events"
  tell process "Microsoft Lync"
    repeat with aWindow in (get every window)
      set aName to get the name of aWindow
      set initialName to ((characters 1 through 12 of aName) as string)
      if (initialName = "Conversation") then
        activate aWindow
        click checkbox 5 of splitter group 1 of aWindow
      end if
    end repeat
  end tell
end tell

I still want to hook it up to a hotkey, and ideally, have a different hotkey for mute and unmute, but that will have to be left for another session. I will hopefully update this post with more details as I figure out how to explain them.

rspec-rails 3 deprecation warnings scripts and fixes

Upon upgrading to rspec 2.99.0, I began to receive deprecation warnings for several things that had issues, and to do a few updates:

Because the project was using its syntax and stub_model I needed to add that functionality back into rspec in the :test group of my Gemfile:

  # Support for its syntax
  gem 'rspec-its', '~> 1.0.1’
 
  # Support for stubbing model in view specs:
  gem 'rspec-activemodel-mocks', '~> 1.0.1'

On top of that I had to do substitutions for be_true, be_false, and_return with block syntax, and change pending to skip for a few pending tests.

I was able to run the following find + sed commands for each of these (note that the .original part is Mac-specific):

find . -name '*.rb' -exec sed -i .original 's/be_true/be_truthy/g' {} +
find . -name '*.rb' -exec sed -i .original 's/be_false/be_falsey/g' {} +
find . -name '*.rb' -exec sed -i .original 's/and_return[ ]*{[ ]*[^} ]*[ ]*}/and_return(\1)/g' {} +
find . -name '*.rb' -exec sed -i .original 's/^[ ]*pending /skip /g' {} +

I haven't completely foolproofed the last two regexes, so I'd make sure to have your work committed for each set of substitutions (and to make sure rspec still passes your tests, of course.)

And the cleanup:

find . -name '*original' -exec rm {} +

Lastly, to quiet the remaining deprecation warnings that I had, I added this to my spec_helper.rb:

Rspec.configure do |config|
# other config code
#
  config.mock_with :rspec do |mocks|
    mocks.yield_receiver_to_any_instance_implementation_blocks = true
  end
 
  config.infer_spec_type_from_file_location!
  config.raise_errors_for_deprecations!
#
# other config code
end

This configuration, as I understand it, will be standard with 3.0:

  mocks.yield_receiver_to_any_instance_implementation_blocks = true

This setting is required for 2.99 because you will unconditionally get a deprecation warning even if you set the type...

  config.infer_spec_type_from_file_location!

And I wanted to raise an error for any other deprecation warnings:

  config.raise_errors_for_deprecations!

After all the dust had settled from 2.99, I upgraded rspec-rails to 3.0.0 and did a bundle update:

  gem 'rspec-rails', '~> 3.0.0' # Test framework

I've unearthed a few deprecation warnings about :should syntax, which I expect to update later.

One misleading deprecation warning:

Requiring `rspec/autorun` when running RSpec via the `rspec` command is deprecated. Called from /Users/tpowell/.rbenv/versions/2.1.1/lib/ruby/gems/2.1.0/gems/activesupport-4.1.1/lib/active_support/dependencies.rb:247:in `require'.

...was actually due to having require 'rspec/autorun' in my spec_helper.rb

mkdir with intermediate directories and rails generate view spec

I've been running into a lot of cases where I need to build intermediate directories for a path. Apparently, the correct option is -p

mkdir -p dir/tree/to/make

From the mkdir man page:

     -p      Create intermediate directories as required.  If this option is not specified, the full path prefix of each operand must already exist.  On the
             other hand, with this option specified, no error will be reported if a directory given as an operand already exists.  Intermediate directories
             are created with permission bits of rwxrwxrwx (0777) as modified by the current umask, plus write and search permission for the owner.

I've assigned it an alias in my .zlogin:

alias mkdirtree='mkdir -p'

Of course, this all came about because I needed to an generate rspec file for a view, which can be done with:

rails g rspec:view name/of/controller action another_action

Results in the following files in the spec/name/of/controller directory:

action.html.erb_spec.rb
another_action.htl.erb_spec.rb

Preventing tinyMCE 4 from inserting <br /> within <code> blocks.

Problem

I was trying to hook in TinyMCE 4 as a editor that allows me to specify code blocks. However, in visual editing mode, <code> blocks ended up having embedded <br /> tags that displayed when rendered.

There is an old plugin, Pre Element Fix, that may have done what I wanted it to do, but it didn't appear to be developed beyond TinyMCE 2.

Solution

It took a bit of work to handle spanning multiline with a match (/[^]*/) and hook into the editor setup (setup: function(editor) {...}).

Complete with initialization code, the following is what I came up with:

fixNewLines = function(content)
{
  var codeBlocks=content.match(/&lt;code.*?&gt;[^]*?&lt;\/code&gt;/m)
 
  if(codeBlocks == null) return content;
  for(var index=0; index &lt; codeBlocks.length; index++) {
    content = content.replace(codeBlocks[index], codeBlocks[index].replace(/&lt;br\s*\/?&gt;/mgi, "\n"));
  }
  return content;
}
 
 
tinymce.init({
    selector: "textarea",
    theme: "modern",
    entity_encoding : "raw",
    plugins: [
        "advlist autolink lists link image charmap print preview hr anchor pagebreak",
        "searchreplace wordcount visualblocks visualchars code fullscreen",
        "insertdatetime media nonbreaking save table contextmenu directionality",
        "emoticons template paste textcolor" ],
    toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
    toolbar2: "print preview media | forecolor backcolor emoticons",
    image_advtab: true,
    templates: [
        {title: 'Test template 1', content: 'Test 1'},
        {title: 'Test template 2', content: 'Test 2'}
    ],
    setup: function(editor) {
      editor.on('BeforeSetContent', function(e) {
        e.content = fixNewLines(e.content);
      });
      editor.on('SaveContent', function(e) {
        e.content = fixNewLines(e.content);
      });
    }
 
});

The key parts are the fixNewLines function, the setup hooks, the code plugin, and (possibly) the entity_encoding:"raw".

When you view the source code, you will still see break tags with the code sections. However, these will be cleared out on save.

Useful References That I Found

Syntax Highlighting Javascript

http://craig.is/making/rainbows

TinyMCE event research

Hook into onExecCommand event with tinymce 4

api:class.tinymce.Editor events

BeforeSetContent event.

SaveContent event.

tinymce.init({
    ...
    setup:function(editor){
        editor.on('BeforeSetContent',function(e){
            console.log('BeforeSetContent event', e);
        });
    }
});

Experiences so far with the 39" Seiki 4k display as a monitor

I bought the 39" Seiki 4k display on a whim as it was only $389 at Amazon and Newegg, after reading a post from another programmer about using it as a coding display. My initial findings and notes:

  • Make sure to have a snugly fitting Phillips head screwdriver before trying to mount the base.
  • Plugged work rMBP into it via the suppled(!) HDMI cable into the HDMI 1 input on the of the display.
  • There are only two scaling options for the rMBP: 3840x2160 (unscaled) and 1440x900 (not really worth the display if you're going to do that.)
  • Dial sharpness down to 0 to be able to read your fonts.
  • Lower brightness below 50. I have it down to 24, but you may have a different preference.
  • Color was a bit too vivid...  I reduced to around 25.
  • I can divide my work window into quadrants and have full view of each:
    • Code window with 4 vertical and 2 horizontal split panes in MacVim.
    • iTerm window divided into 4 80x25 quadrants.
    • Browser window
    • Evernote window
  • The internal speakers on the TV sound like a cheap pair of speakers. More output than the rMBP internal speakers, but sound quality is a bit worse.
  • iTunes visualizer and YouTube videos don't show the weakness in the 30Hz refresh rate, only a bit of higher speed mouse tracking has even remotely exposed it for me, but I'm don't a desktop gamer.
  • Mouse speed vs being able to see your mouse pointer in motion can be a bit of a challenge. The larger display is more conducive to keyboard input for me.
  • Attempting to use the entire screen at once seems to introduce lag from eye-tracking, I've found it more useful to divide work areas on the screen. The benefit then comes from having everything on top at once.

Filter chain halted as :find_page rendered or redirected in refinerycms

I ended up coming across this issue in Refinery CMS after switching databases.

I had forgotten that I had swapped out databases because I had moved on to changing some other configuration bits in following the RailsCast for Refinery CMS.

Fortunately, I found note on Refinery's Getting Started page that deals with this:

If you get a 404 error on the homepage, try running the rake db:seed and then restarting the server.

rails generate paperclip_database:migration getting protected method `migration_file_name' error

Quick fix (put this in application.rb or similar in order to run the rails generate paperclip_databasee:migration command):

module PaperclipDatabase
  module Generators
    class MigrationGenerator
      public :migration_file_name
    end
  end
end

There are two errors causing this error, one in paperclip and one in paperclip_database. Not sure what changes to Rails 4 caused this, but the issue is fixed in this commit in paperclip, which probably needs to be mirrored in paperclip_database. (Even if I point to the github repo for paperclip, I still get the error due to protected being specified on paperclip_database as well.

The error only appears to affect the generator.

If you'd rather not have a temporary monkey patch, you can write the migration by hand:

Example (for a User with an avatar attachment):

class CreateUserAvatar < ActiveRecord::Migration
  def self.up
    create_table :avatars do |t|
      t.integer    :user_id
      t.string     :style
      t.binary     :file_contents
    end
  end
 
  def self.down
    drop_table :avatars
  end
end