Archive
words and words and words
News javascript jquery html5
setting a html5 data attribute with jquery

Abstract

I have a single bootstrap modal, which is called from different places, and so the modal contains some data-* attributes I want to set before showing it. Just using the .data() offered by jquery does not work.

Detailed example

Suppose you have mark-up like this:

<div data-some-important-value="123">

Asking the value is quite easy:

$('[data-some-important-value]').data('some-important-value')

And, according to the documentation, setting the data on a DOM element, should be as easy as

$('[data-some-important-value]').data('some-important-value', 'new-value')

If you would try this in the console, you could verify that does not work. This is where it gets confusing (to me). Apparently the .data() offered by jquery existed before the HTML5 data-* elements did, and they nicely integrated them. But the data-* are only loaded once, and never written back to the document.

To still be able to do this, use the .attr() method instead:

$('[data-some-important-value]').attr('data-some-important-value', 'new-value')

Now I only have to include one modal "template" in my HTML, and set the data-* attributes to customize the behaviour.

More ...
Technology ruby
[ruby] hate private methods? use protected instead

I started out writing something like the following:

If I could change just one thing in ruby, I would change how private works. Aaarrgghh.

For instance, I am trying to implement an equality of bounding boxes in ruby. I would presume I could write something like:

class BoundingBox

  attr_accessor :xmin, :ymin, :xmax, :ymax

  def initialize(xmin, ymin, xmax, ymax)
    @xmin = xmin
    @ymin = ymin
    @xmax = xmax
    @ymax = ymax
  end

  def ==(other)
    other.class == self.class && self.state == other.state
  end
  alias_method :eql?, :==

  private

  def state
    [@xmin, @ymin, @xmax, @ymax]
  end

end

Because I am inside the scope of the class, I am allowed to access the private methods. That is how it is supposed to be. But no, ruby says something silly like:

private methods cannot be called with an explicit receiver

So you have to resort to something ludicrous like writing

def ==(other)
    other.class == self.class && self.send(:state) == other.send(:state)
  end

This works. So I could have left it there. But wait: protected is exactly what I want. I have been using it wrong completely.

So in short:

  • use public for your public API of your class (obviously)
  • use protected for methods that are not part of your API, but other instances of the same class need to be able to reach (e.g. for equality checking, sorting, ...)
  • use private for methods that are only used inside the class, and only refer to the implicit receiver.

So if in the first example I change private to protected, it just works. I have been doing it wrong all along.

More ...
Technology ruby method_missing rails
[rails] store your settings in a model

Most of the times I use a config.yml to store application settings, that I want to be able to change quickly between environments, servers, deployments. But what with settings that need to be changed on the fly, by a user?

I create a small model, with three fields.

rails g model Setting name:string description:string value:string

I use a seed file to define the different settings. Settings are checked in code, but I can not preload them, since a user might change them. So first I added a method as_hash that loads all settings, and I can then directly use a hash, but that gets wordy quickly.

What if ... I could provide a method on the class Setting for each setting in the database? That would be really nice. This seems like a job for ... method-missing-man Special superpower: seeing places where method_missing could be used :)

class Setting < ActiveRecord::Base

  validates_presence_of :name

  def self.as_hash
    settings = {}
    Setting.all.each do |setting|
      settings[setting.name.to_sym] = setting.value
    end
    settings
  end

  # offer all settings as methods on the class
  def self.method_missing(meth, *args, &block) #:nodoc:
    @all_settings ||= Setting.as_hash
    if @all_settings.keys.include?(meth)
      @all_settings[meth]
    else
      super
    end
  end
end

For documentation, the test:

context "convenience: define methods for all settings" do
  before do
    Setting.instance_variable_set('@all_settings', nil)
    Setting.create(name: 'my_other_test_setting', value: '123ZZZ')
  end
  it "Setting.my_other_test_setting returns the correct result" do
    Setting.my_other_test_setting.should == '123ZZZ'
  end
  it "an unexisting setting behaves as a normal missing method" do
    expect {
      Setting.this_setting_does_not_exist
    }.to raise_exception(NoMethodError)
  end
end

I love ruby :) :)

More ...
News
[postgis] fixing missing rt-postgis2.0

TL;DR

If you are using brew to manage your postgresql/postgis install, and you suddenly cannot access any postgis functionality, with the error that rtpostgis-2.0.so cannot be found, check your json-c version, I had to do

brew switch json-c 0.10

to get it working.

The long and dirty story

I had created a new database, but for some reason I could not add a geometry column, so I was thinking, maybe, somehow my POSTGIS extension needs to be (re)activated. And when I tried this I got the the obscure error

could not load library "/usr/local/Cellar/postgresql/9.2.3/lib/rtpostgis-2.0.so": dlopen(/usr/local/Cellar/postgresql/9.2.3/lib/rtpostgis-2.0.so, 10): Library not loaded: /usr/local/opt/sqlite/lib/libsqlite3.0.8.6.dylib Referenced from: /usr/local/lib/libgdal.1.dylib

Whaaaaaattttt????

Maybe my postgis installation is somehow corrupt, so I tried brew install postgis. Wronggggg move. Suddenly I am installing postgresql 9.3.4 too?

Ok. I did not see an alternative. This of course ment I should upgrade my database. First step: install postgresql 9.3.4 and postgis. Then I tried to follow this upgrade procedure. In short I issued the following commands:

initdb /usr/local/var/postgres9.3 -E utf8
pg_upgrade -d /usr/local/var/postgres -D /usr/local/var/postgres9.3 -b /usr/local/Cellar/postgresql/9.2.3/bin/ -B /usr/local/Cellar/postgresql/9.3.4/bin/ -v

and that failed? I got almost the same error, but now a bit more verbose:

PG::UndefinedFile: ERROR: could not load library "/usr/local/Cellar/postgresql/9.2.3/lib/postgis-2.0.so":   
    dlopen(/usr/local/Cellar/postgresql/9.2.4/lib/postgis-2.0.so, 10): Symbol not found: _json_tokener_errors
Referenced from: /usr/local/Cellar/postgresql/9.2.4/lib/postgis-2.0.so
Expected in: /usr/local/lib/libjson.0.dylib
   in /usr/local/Cellar/postgresql/9.2.4/lib/postgis-2.0.so

What? Json? And that led me to the answer: I had to switch my json-c version:

brew switch json-c 0.10

Restarted my pg_upgrade which now seemed to work, but failed at the end, that postgis-2.0.so and rtpostgis-2.0.so were not loadable. Sigh. These were of course compiled against the new json-c (I think?).

I switched the json-c version back to 0.11 and then I started my postgres process again. This showed my that my databases were NOT upgraded.

This almost feels like dll hell al over again.

Should I uninstall postgis, do db_upgrade and install it again? Go back to 9.2.3?

For the moment I switched back to 9.2.3 and opened an issue on the homebrew. I hope somebody can help me.

brew switch postgresql 9.2.3
 brew switch json-c 0.10

Not sure what will break, because something needed to install json-c 0.11 ? At least for now I am good. I hope.

[UPDATE] Nope. It only partly works now. The errors I saw were:

after brew switch json-c 0.10 :

PG::UndefinedFile: ERROR: could not load library "/usr/local/Cellar/postgresql/9.2.3/lib/rtpostgis-2.0.so": dlopen(/usr/local/Cellar/postgresql/9.2.3/lib/rtpostgis-2.0.so, 10): Library not loaded: /usr/local/lib/libjson-c.2.dylib Referenced from: /usr/local/opt/liblwgeom/lib/liblwgeom-2.1.1.dylib Reason: image not found

after brew switch json-c 0.11

PG::UndefinedFile: ERROR: could not load library "/usr/local/Cellar/postgresql/9.2.3/lib/postgis-2.0.so": dlopen(/usr/local/Cellar/postgresql/9.2.3/lib/postgis-2.0.so, 10): Symbol not found: _json_tokener_errors Referenced from: /usr/local/Cellar/postgresql/9.2.3/lib/postgis-2.0.so Expected in: /usr/local/lib/libjson.0.dylib in /usr/local/Cellar/postgresql/9.2.3/lib/postgis-2.0.so

So I was stuck. Reverting to the old version did not fix it.

I was able to get my situation rectified by doing a "clean" install of postgresql92 which installed postgresql 9.2.8.

brew install postgresql92
brew link --overwrite postgresql92
brew install postgis20
launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

And now I am good. On version 9.2.8. Hehe.

conclusion

I have no clear conclusion or solution. Somehow my json-c got upgraded, which messed up my postgis installation. I guess installing the new version of postgis, messed up my old version of postgis (since now one file was linked to json-c.0.11 and the other against json-c.0.10).

However I did find a clean solution: upgrading to postgresql92 and postgis20, now nicely linked against json-c 0.11.

If you encounter the same error: switch your json-c version, before trying anything else, and then I hope you should be good to go (no need to upgrade).

More ...
News
[rails 4.1] when the rails command just hangs

For one of my projects I am using rails 4.1 (bleeding edge! yeah :) ) and suddenly noticed, that after opening my laptop in the morning my normal rails commands, like

$> rails c
$> rails g migration Bla name description some_more_fields

just ... were hanging and nothing happened??? Like they were waiting for further input. Upon closer investigation, I assumed that the connection to the spring process was lost/corrupt (I move between networks a lot? maybe that could explain it).

For those unaware, as I was, spring is a Rails application preloader. It speeds up development by keeping your application running in the background so you don't need to boot it every time you run a test, rake task or migration. Of course when that connection is lost, or corrupt, it hangs.

A simple

$> spring stop

stops the spring server, after which any rails command will restart it automatically. Fixed :)

More ...
News
[rails] using foundation 5 without installing bower

Starting with ZURB Foundation 5, they use Bower to distribute the assets, and in their "getting started" guide they propose to install bower.

I have not yet installed bower myself, but there is a really easy alternative: use rails-assets.org.

At the top of your Gemfile add a source line:

source 'https://rubygems.org'
source 'https://rails-assets.org' ## <---- add this line

and then add the gem

gem 'rails-assets-foundation'

In your application.js add

//= require foundation

And in your application.css add

*= require foundation

Done! :)

More ...
News oracle
[oracle] changing the value of a sequence

According to oracle documentation, to change a value of a sequence, you have to drop and recreate it, using the following command:

CREATE SEQUENCE table_name_seq START WITH 12345;

But there are some easy ways to change the value of an existing sequence too.

If you want to increment the current value by 500, you can just use

select your_sequence_name.nextval from dual connect by level <= 500;

If you want to decrement it, you can do that as follows:

alter sequence id_sequence increment by -500;
select id_sequence.nextval from dual;
alter sequence id_sequence increment by 1;

(of course this can also be used to increment it, but the connect by level trick is easier then)

More ...
News activerecord rails4 ruby on rails
[rails 4] add a reference to a table with another name

They default way in rails 4 to add foreign keys is simply

add_reference :people, :user

And this will add a column user_id to the people table, if the table exists. I have been looking in the rails code where this is handled, and it is really straightforward.

Note that standard rails does not really do anything for referential integrity, it creates the correct columns and an index if so specified.

But we use the schema_plus gem, for two reasons:

  • it does handle referential constraints correctly (on the database level)
  • it allows to specify the creation of views in a migration more cleanly

So, with schema_plus, if you write something like:

add_reference :people, :owner

and there is no owners table, this will give an error.

So instead you need to write :

add_reference :people, :owner, references: :users

This will correctly generate an owner_id which is a foreign key to users(id).

If you want to create a self-referential link, that is really easy. Just write

add_reference :people, :parent

This will create a self-referential link. Awesome :)

For completeness, the add_reference will add a reference columns to an already existing table. The same can be done when creating (or changing) a table with the following syntax:

create_table :people do |t| 
  t.references :owner, references: :users
  t.references :parent
end

So, in short, if you were not using the schema_plus gem already, start doing so now :)

More ...
News rails4 ruby on rails
How to clean assets in rails 4

Gentle reminder, do not forget, in rails 4

rake assets:clean

seems to work, but actually does nothing. That is not entirely true: it only cleans the old assets, leaving the three most recent versions of the assets intact. So it is a like a mild cleaning, a throw-away-the-garbage-clean, a bring-those-old-clothes-you-never-wear-to-the-thriftstore-clean.

But sometimes that does not cut it. Sometimes, don't ask me why, building my assets does not seem to work, my code is just not being picked up. And then you need to do use brute force cleaning (throw everything out). Run

rake assets:clobber

to actually clean the assets. The logic or meaning is lost on my me (clobber?), but this works.

More ...
Technology ruby windows ruby on rails
Run rails 2.3.18 using ruby 1.8.7 on windows server 2012

For my current job we have two 2.3.5 rails sites, of which I already succesfully upgraded one to rails 4. For the other we still need to start the migration, and we were asked to install new windows servers to run the rails servers on in the meantime (let's not digress why they choose windows, in a business environment Windows servers are still preferred, and let's be honest; they are easier to maintain and manage then *nix servers at first sight).

So whatever: I had to install the rails 2.3.5 on a new Windows 2012 server.

This proved problematic, since the new ruby 1.8.7 comes with the new rubygems, and this does not work nicely with rails 2.3.5.

So step 1: install the old ruby 1.8.7 (p302), the old gems and run the rails server. This worked.

But then I saw this one thing I really needed to improve. So I migrated the project to the latest 1.8.7 and rails 2.3.18, use bundler for gem dependencies. On my development box this worked like a charm (Macbook Pro). So then I deployed this back on the server, and then the following happened:

C:/Ruby187/lib/ruby/1.8/pathname.rb:290:in `[]': no implicit conversion from nil to integer (TypeError)
    from C:/Ruby187/lib/ruby/1.8/pathname.rb:290:in `chop_basename'
    from C:/Ruby187/lib/ruby/1.8/pathname.rb:343:in `cleanpath_aggressive'
    from C:/Ruby187/lib/ruby/1.8/pathname.rb:331:in `cleanpath'
    from C:/Ruby187/lib/ruby/gems/1.8/gems/rails-2.3.18/lib/rails/rack/log_tailer.rb:9:in `initialize'
    from C:/Ruby187/lib/ruby/gems/1.8/gems/rack-1.1.6/lib/rack/builder.rb:54:in `new'
    from C:/Ruby187/lib/ruby/gems/1.8/gems/rack-1.1.6/lib/rack/builder.rb:54:in `use'
    from C:/Ruby187/lib/ruby/gems/1.8/gems/rack-1.1.6/lib/rack/builder.rb:73:in `call'
    from C:/Ruby187/lib/ruby/gems/1.8/gems/rack-1.1.6/lib/rack/builder.rb:73:in `to_app'
    from C:/Ruby187/lib/ruby/gems/1.8/gems/rack-1.1.6/lib/rack/builder.rb:71:in `inject'
    from C:/Ruby187/lib/ruby/gems/1.8/gems/rack-1.1.6/lib/rack/builder.rb:73:in `each'
    from C:/Ruby187/lib/ruby/gems/1.8/gems/rack-1.1.6/lib/rack/builder.rb:73:in `inject'
    from C:/Ruby187/lib/ruby/gems/1.8/gems/rack-1.1.6/lib/rack/builder.rb:73:in `to_app'
    from C:/Ruby187/lib/ruby/gems/1.8/gems/rails-2.3.18/lib/commands/server.rb:95
    from script/server:3:in `require'
    from script/server:3

What was going on here? Apparently in the rails/rack/logtailer.rb is the following code:

class LogTailer
  def initialize(app, log = nil)
    @app = app

    path = Pathname.new(log || "#{::File.expand_path(Rails.root)}/log/#{Rails.env}.log").cleanpath

And the cleanpath is somehow crashing. I tried googling this, to no avail.

Of course:

  • rails 2.3.18: who uses that still?
  • ruby 1.8.7 is deprecated
  • and deploying on windows servers

So I was on my own. I tracked the error down to the cleanpath_agressive which called the chop_basename recursively to remove superfluous . and .. redirections.

I am guessing the problem is that on windows, a path starts with a drive-letter, like D:\ or C:\ which messes up the ending of the cleanpath_aggressive loop.

Instead of really diving in, the path handed down to cleanpath in my case, did not need any cleaning, and furthermore, an uncleaned path would still work.

So I added an initializer config\cleanpath_bug_fix.rb with the following code:

if RUBY_PLATFORM =~ /mingw/
  # on windows the Pathname.cleanpath crashes on windows paths, instead of fixing it thoroughly
  # just ignore it
  class Pathname
    def cleanpath_aggressive
      self
    end
  end
end

Now my rails 2.3.18, using ruby 1.8.7p374 runs on Windows Server 2012R2. Woot ;)

More ...