string snippets

How to fix "Cannot modify SafeBuffer in place"

Tagged string, safebuffer  Languages ruby

If you get this error:

Cannot modify SafeBuffer in place
ruby/1.8/gems/activesupport-3.0.9/lib/active_support/core_ext/string/output_safety.rb:119:in gsub!'
ruby/1.8/xmlrpc/create.rb:54:in text'

You might need to upgrade haml, or if that doesn't help you need to convert the SafeBuffer to a String. In this case it's the parameters given to an XML-RPC call that need to be converted to strings:


In other words the solution is to update your gem or use .to_str.

How to use Rails' form_for with a PostgreSQL array

Tagged array, form_for, string, postgresql  Languages ruby

Using Rails’ form_for with a PostgreSQL array, for example, user roles can be done as follows:


class CreateProjectMembers < ActiveRecord::Migration[6.0]
  def change
    create_table :project_members, id: :uuid do |t|
      t.string :roles, array: true, default: []


class ProjectMember < ApplicationRecord
  validate :validate_roles
  ROLES = %w[administrator collaborator].freeze

  def validate_roles
    return if roles.is_a?(Array) && roles.all? { |d| ROLES.include?(d) }

    errors.add(:roles, :invalid)

View (slim-lang):

= form @project_member do |f|
    = f.label :roles, 'Roles'
    = f.check_box :roles, { label: 'Administrator', multiple: true }, 'administrator', nil
    = f.check_box :roles, { label: 'Collaborator', multiple: true }, 'collaborator', nil


class ProjectMembersController < ApplicationController
  def update
    if @project_member.update(project_member_params)

  def project_member_params
    params.require(:project_member).permit(roles: [])

Note that if you have a “has_many through” relationship, instead of a PostgreSQL array, you can simply use:

= f.collection_check_boxes(:locale_ids, Locale.all, :id, :language) do |b|


Converting a string to a number with CRC

Tagged conversion, crc, number, string  Languages ruby

CRC can be used to convert a string into a number:

require 'zlib'
integer = Zlib.crc32('snippet')
=> 2518453461
=> 2656977832

The CRC algorithm is normally used to detect changes or errors in large chunks of data.