<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Adam Wróbel</title>
    <description>I'm a web and app developer. On this blog I occasionally used to write about stuff that might be of interest to other developers.</description>
    <link>https://adamwrobel.com/blog</link>
    <atom:link href="https://adamwrobel.com/blog/feed.xml" rel="self" type="application/rss+xml"/>
    <lastBuildDate>Mon, 15 Jun 2026 07:35:37 GMT</lastBuildDate>
      <item>
        <title>Protocol-based dependency injection in Swift</title>
        <description>&lt;p&gt;I’ve been using protocols for dependency injection in Swift for a while, but recently
I came up with a nifty little function that helps with the task using generics. Using
protocols for dependency injection is a great way to abstract your code and make it more
flexible. Say you get an unnamed view controller as a &lt;code&gt;segue.destinationViewController&lt;/code&gt;
property. In Swift you don’t need to cast it to specific class instance. Instead you
can check for protocol conformance. “Is this X” vs “is this something that wants Y” –
identity versus function. If later you add a segue to another conforming controller you
won’t have to add a line of code.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;p&gt;So here’s that generic function that helps with this pattern:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;func injectDependencies&amp;#x3C;Protocol&gt;(
  into viewController: UIViewController,
  @noescape block: (Protocol) -&gt; Void
) {
  if let conformingController = viewController as? Protocol {
    block(conformingController)
  }
  for controller in viewController.childViewControllers {
    injectDependencies(into: controller, block: block)
  }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;&lt;p&gt;This will traverse any table or collection view controllers that you might be using.&lt;/p&gt;
&lt;p&gt;So in my app any controller that talks to the network does so through CacheManager which
handles the requests and returns results using &lt;code&gt;NSFetchedResultsController&lt;/code&gt; from the
cache. I create the cache manager once in AppDelegate and propagate it to any controller
that might need it.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;func application(
  application: UIApplication,
  didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?
) -&gt; Bool {
  cacheManager = CacheManager()

  injectDependencies(into: window!.rootViewController!) {
    (controller: ControllerWithNetworkAccess) in
    controller.cacheManager = cacheManager
  }

  return true
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;&lt;p&gt;And then in segues of controllers that reference cacheManager:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
  injectDependencies(into: segue.destinationViewController) {
    (controller: ControllerWithNetworkAccess) in
    controller.cacheManager = cacheManager
  }
}&lt;/code&gt;&lt;/pre&gt;
</description>
        <pubDate>Tue, 21 Jun 2016 00:00:00 GMT</pubDate>
        <link>https://adamwrobel.com/blog/2016/06/21/protocol-based-dependency-injection-in-swift/</link>
        <guid isPermaLink="true">https://adamwrobel.com/blog/2016/06/21/protocol-based-dependency-injection-in-swift/</guid>

      </item>
      <item>
        <title>Swift wrapper for Grand Central Dispatch</title>
        <description>&lt;p&gt;I’ve written another Swift wrapper for GCD. Original C API does not fit Swift at all. It’s
tedious and not very readable. Until recently I’ve been using this great
&lt;a href=&quot;https://gist.github.com/Inferis/0813bf742742774d55fa&quot; target=&quot;_self&quot; rel=&quot;&quot;&gt;gist&lt;/a&gt; by &lt;a href=&quot;https://twitter.com/Inferis&quot; target=&quot;_self&quot; rel=&quot;&quot;&gt;Tom
Adriaenssen&lt;/a&gt;, but now I needed to use other QoS queues beside
main and the background queue. Other default global queues available in GCD are:
“Interactive”, “User Initiated” and “Utility”.&lt;/p&gt;
&lt;p&gt;Problem with Tom’s implementation was that it declared three class-level methods for every
queue it supported. This approach is untenable for more than two queues. Luckily with
Swift we can extend types like &lt;code&gt;dispatch_queue_t&lt;/code&gt; or &lt;code&gt;dispatch_group_t&lt;/code&gt; and define methods
that will reference &lt;code&gt;self&lt;/code&gt;. This way we can implement &lt;code&gt;sync&lt;/code&gt;, &lt;code&gt;async&lt;/code&gt;, &lt;code&gt;after&lt;/code&gt; methods
that will be available on every queue including custom queues created by user.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;p&gt;Don’t worry about performance when compared with static definitions. I’ve declared
the methods final giving the compiler hint that it can optimize and inline these
calls. There won’t be any type checking or vtable lookups at runtime. So using
&lt;code&gt;dispatch.interactive.async {/*code*/}&lt;/code&gt; should generate the same binary as:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0)) {
  /* code */
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;&lt;p&gt;One problem I encountered was protection against deadlock when calling &lt;code&gt;sync&lt;/code&gt; on the
currently running queue. Tom had this small check only in the main queue &lt;code&gt;sync&lt;/code&gt;
implementation (background queue wasn’t protected):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class func main(block: dispatch_block_t) {
  if NSThread.isMainThread {
    block()
  }
  else {
    dispatch_sync(dispatch_get_main_queue(), block)
  }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;&lt;p&gt;This solution obviously works only for the main queue. But I needed to implement a method
that will work with any queue. At first I thought about using &lt;code&gt;dispatch_get_current_queue&lt;/code&gt;
and comparing it with &lt;code&gt;self&lt;/code&gt;, but it turns out that the method is deprecated in C and is
not available in Swift at all. I decided I can tag queues using queue specific context and
check the tag using &lt;code&gt;dispatch_get_specific&lt;/code&gt;. I admit it’s a bit of a hack but it works for
any queue. Since it adds a few extra cycles I’ve limited this to a separate method which
I’ve called &lt;code&gt;safeSync&lt;/code&gt;. If you don’t need this extra protection then stick to &lt;code&gt;sync&lt;/code&gt; and
you’ll get the same safety and performance as when calling &lt;code&gt;dispatch_sync&lt;/code&gt; directly.&lt;/p&gt;
&lt;p&gt;So finally here’s a usage overview:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// this will wait for completion and will deadlock when called from main queue
dispatch.main.sync {
  print(&quot;hello from main queue&quot;)
}

// this will return immediately
dispatch.utility.async {
  print(&quot;working with the Utility QoS&quot;)
}

// a safe sync operation that can be sent from any queue to any queue
dispatch.main.safeSync {
  print(&quot;safety in mind&quot;)
}

// this schedules a delayed block
dispatch.main.after(2.5) {
  printWithTime(&quot;hello from main after 2.5 seconds&quot;)
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;&lt;p&gt;I’ve also thrown in support for grouping tasks:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let group = dispatch.createGroup()

// schedule some asynchronous tasks
dispatch.interactive.async(group) {
  print(&quot;part of the job&quot;)
}
dispatch.user.async(group) {
  print(&quot;another part of the job&quot;)
}

// schedule asynchronous finalizer
group.notify {
  print(&quot;this will be executed when all of the group tasks complete&quot;)
}

// or synchronously wait for the group to complete
group.wait()

print(&quot;group completed&quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;&lt;p&gt;Below is the entire implementation. It’s so small that there’s no point making it an
external dependency. Just drop the code somewhere in your project and enjoy. You can
also star this
&lt;a href=&quot;https://gist.github.com/amw/9d62f247d0de3fa08e5facc59bc91037&quot; target=&quot;_self&quot; rel=&quot;&quot;&gt;gist&lt;/a&gt;
to get notified about any updates I make.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;//
//  dispatch.swift
//
//  Created by Adam Wróbel. Read more at:
//  http://adamwrobel.com/blog/2016/05/08/swift-gcd-wrapper/
//

import Foundation

internal extension dispatch_queue_t {
  /// Submits a block for asynchronous execution on this queue and returns
  /// immediately.
  final func async(block: dispatch_block_t) {
    dispatch_async(self, block)
  }

  /// Submits a block for asynchronous execution on this queue and associates
  /// the block with given group.
  final func async(group: dispatch_group_t, block: dispatch_block_t) {
    dispatch_group_async(group, self, block)
  }

  /// Submits a block object for execution on this queue and waits until that
  /// block completes.
  ///
  /// Calling this method on the current queue results in deadlock.
  final func sync(block: dispatch_block_t) {
    dispatch_sync(self, block)
  }

  /// Submits a block object for execution on this queue and waits until that
  /// block completes.
  ///
  /// Prevents deadlock by executing the block immediately if called on the
  /// current queue. Performing this safety check adds a little overhead when
  /// compared with `sync`.
  final func safeSync(block: dispatch_block_t) {
    isCurrent() ? block() : sync(block)
  }

  /// Enqueue a block for execution after specified number of seconds.
  final func after(seconds: Double, block: dispatch_block_t) {
    let when = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * 1_000_000_000))
    dispatch_after(when, self, block)
  }

  /// Asynchronously runs a block on this queue when the group's tasks are
  /// complete.
  final func after(group: dispatch_group_t, block: dispatch_block_t) {
    group.notify(self, block: block)
  }
}

internal extension dispatch_group_t {
  /// Waits until all of the group's tasks are complete.
  final func wait() {
    dispatch_group_wait(self, DISPATCH_TIME_FOREVER)
  }

  /// Asynchronously runs a block on the main queue when the group's tasks are
  /// complete.
  final func notify(block: dispatch_block_t) {
    dispatch_group_notify(self, dispatch.main, block)
  }

  /// Asynchronously runs a block on the given queue when the group's tasks are
  /// complete.
  final func notify(queue: dispatch_queue_t, block: dispatch_block_t) {
    dispatch_group_notify(self, queue, block)
  }
}

final internal class dispatch {
  /// Serial queue associated with the application's main thread.
  class var main: dispatch_queue_t {
    return dispatch_get_main_queue()
  }

  /// Parallel queue used for work that is not user initiated or visible.
  class var bg: dispatch_queue_t {
    return dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)
  }

  /// Parallel queue used for work which the user is unlikely to be immediately
  /// waiting for the results.
  class var utility: dispatch_queue_t {
    return dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)
  }

  /// Parallel queue used for work that has been explicitly requested by the
  /// user, and for which results must be immediately presented in order to
  /// allow for further user interaction.
  class var user: dispatch_queue_t {
    return dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)
  }

  /// Parallel queue used for work directly involved in providing an
  /// interactive UI.
  class var interactive: dispatch_queue_t {
    return dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0)
  }

  /// Creates a new group with which block objects can be associated.
  class func createGroup() -&gt; dispatch_group_t {
    return dispatch_group_create()
  }
}

// Private extensions used exclusively to support `safeSync`

private extension dispatch {
  static var identityKey = UnsafePointer&amp;#x3C;Int8&gt;(bitPattern: 1234)

  class var currentIdentity: UnsafeMutablePointer&amp;#x3C;Void&gt; {
    return dispatch_get_specific(identityKey)
  }
}

private extension dispatch_queue_t {
  /// Uses queue specific context to determine if we're executing on this queue.
  func isCurrent() -&gt; Bool {
    var ourIdentity = identity

    if ourIdentity == nil {
      ourIdentity = UnsafeMutablePointer&amp;#x3C;Void&gt;(label)
      dispatch_queue_set_specific(self, dispatch.identityKey, ourIdentity, nil)
    }

    return ourIdentity == dispatch.currentIdentity
  }

  var label: UnsafePointer&amp;#x3C;Int8&gt; {
    return dispatch_queue_get_label(self)
  }

  var identity: UnsafeMutablePointer&amp;#x3C;Void&gt; {
    return dispatch_queue_get_specific(self, dispatch.identityKey)
  }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;&lt;p&gt;P.S. You’ll notice that I like to put all private methods in separate private
extensions. This way you keep these methods away from the public interface and you don’t
have to separately mark each of them as private.&lt;/p&gt;
&lt;p&gt;P.S.S. I think the block parameter in &lt;code&gt;dispatch_sync&lt;/code&gt; should be marked with &lt;code&gt;noescape&lt;/code&gt;
attribute, but GCD is a C API and &lt;code&gt;noescape&lt;/code&gt; is only supported in Swift and Objective-C.&lt;/p&gt;
</description>
        <pubDate>Sun, 08 May 2016 00:00:00 GMT</pubDate>
        <link>https://adamwrobel.com/blog/2016/05/08/swift-gcd-wrapper/</link>
        <guid isPermaLink="true">https://adamwrobel.com/blog/2016/05/08/swift-gcd-wrapper/</guid>

      </item>
      <item>
        <title>Open text editor on offenses found by RuboCop</title>
        <description>&lt;p&gt;I’ve recently added RuboCop to one of my existing, large Ruby projects. A lot of the style
adjustments RuboCop was able to apply automatically, but a significant number of files was
still left for me to fix.&lt;/p&gt;
&lt;p&gt;Opening each file manually seemed like a hassle so I’ve prepared this script that opens
&lt;code&gt;$EDITOR&lt;/code&gt; on each offense, waits for user to modify the file and goes to the next offense.
It’s tuned for MacVim/Vim, but any editor that doesn’t detach from shell should work.
This saved me tremendous amounts of time.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;pre&gt;&lt;code&gt;require &quot;rubocop&quot;

class OpenEditor &amp;#x3C; RuboCop::Formatter::ProgressFormatter
  VimFamily = %w{vim gvim mvim}

  def report_file file, offenses
    super

    if editor_supports_lines?
      offenses.each do |offense|
        run_editor file, offense unless offense.corrected?
      end
    else
      run_editor file
    end
  end

  def editor
    ENV[&quot;EDITOR&quot;]
  end

  def editor_supports_lines?
    VimFamily.include? editor
  end

  def run_editor file, offense = nil
    if offense
      args = args_with_offense file, offense
    else
      args = args_without_offense file
    end

    original_modification_time = File.mtime file

    system editor, *args

    return if original_modification_time != File.mtime(file)

    output.puts &quot;No changes made to the file. Aborting.&quot;
    exit 1
  end

  def args_with_offense file, offense
    case editor
    when *VimFamily
      # Text vim will hide our console output, so we need to echo the message again
      # inside vim.
      message = offense.message.to_s
        .gsub('&quot;', &quot;double quote&quot;)
        .gsub(&quot;'&quot;, &quot;quote&quot;)

      [
        &quot;+#{offense.line}&quot;,           # go to line
        &quot;-f&quot;,                         # gvim/mvim will not detach from shell
        &quot;-c&quot;, &quot;echomsg '#{message}'&quot;,
        file
      ]
    else
      [file]
    end
  end

  def args_without_offense file
    [file]
  end
end&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;&lt;p&gt;And use it like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;rubocop -r ./editor.rb -f OpenEditor&lt;/code&gt;&lt;/pre&gt;
</description>
        <pubDate>Sat, 17 Oct 2015 00:00:00 GMT</pubDate>
        <link>https://adamwrobel.com/blog/2015/10/17/open-text-editor-on-offenses-found-by-rubocop/</link>
        <guid isPermaLink="true">https://adamwrobel.com/blog/2015/10/17/open-text-editor-on-offenses-found-by-rubocop/</guid>

      </item>
      <item>
        <title>Converting or fixing MySql table character set</title>
        <description>&lt;p&gt;Recently I had to migrate some very old website to a new server. When that website was
first deployed the MySql server was at version 4.0 and had no internal support for
character sets. When MySql 4.1 first appeared and assigned each table and column their own
character set it was very common for applications to store data with different actual
encoding than the meta data specified in the database schema.&lt;/p&gt;
&lt;p&gt;This led to problems during data migrations and also when browsing database with clients
that specify their connection encoding. Whenever a connection encoding different than
default (latin1) was specified MySql would try to convert the table contents to the
requested coding and fail miserably if the data’s real encoding was different than what
was stored in table definition. In my case I was storing utf8 data while MySql was
convinced it was latin1. When in a situation like this you have two options.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;p&gt;If you’re able to SSH to the machine with the database then you can work around this
problem during export by specifying default character set during &lt;code&gt;mysqldump&lt;/code&gt;. If it
matches the table’s character set then MySql doesn’t perform any conversion. Then you have
to adjust the meta data in the data definition statements inside the sql dump. Something
like this might work:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;mysqldump -u user --default-character-set=latin1 -p database | \
sed -e &quot;s/ DEFAULT CHARSET=latin1;$/ DEFAULT CHARSET=utf8;/&quot; | \
sed -e &quot;s/!40101 SET NAMES latin1 /!40101 SET NAMES utf8 /&quot; &gt; \
  good-encoding.sql&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;&lt;p&gt;This is a safe procedure because you’re not modifying any data on the server only creating
a separate dump.&lt;/p&gt;
&lt;p&gt;Unfortunately I didn’t have shell access to the machine that was running my app, so I had
to modify the data in place before doing the export with phpMyAdmin.&lt;/p&gt;
&lt;p&gt;The &lt;a href=&quot;http://dev.mysql.com/doc/refman/5.1/en/alter-table.html&quot; target=&quot;_self&quot; rel=&quot;&quot;&gt;documentation&lt;/a&gt; mentions
a command in &lt;code&gt;ALTER TABLE&lt;/code&gt; statement that can change table’s character encoding, but that
command also performs data conversion and can corrupt data if it’s meta information is
incorrect. That same page mentions that if you want to skip the conversion then you have
to add an intermediate step and convert the column to &lt;code&gt;BINARY&lt;/code&gt;/&lt;code&gt;VARBINARY&lt;/code&gt;/&lt;code&gt;BLOB&lt;/code&gt; type,
change the table encoding and then convert the column back to it’s normal type. Like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ALTER TABLE `pages` MODIFY `title` varbinary(30) NOT NULL default '';
ALTER TABLE `pages` CHARACTER SET utf8;
ALTER TABLE `pages` MODIFY `title` varchar(30) NOT NULL default '';&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;&lt;p&gt;After executing these statements the only thing modified should be the meta information
stored in table definition. The data will remain unchanged.&lt;/p&gt;
&lt;p&gt;I’ve written a little Ruby script that parses data definition statements generated by
&lt;code&gt;mysqldump&lt;/code&gt; or phpMyAdmin (select “no-data” option during export) and prepares these
statements automatically. Note that it will not convert columns that have explicit
character set definition (don’t use table default).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#!/usr/bin/ruby

targetEnc = 'utf8'
targetEnc = ARGV[0] unless ARGV.size &amp;#x3C; 1

f = $stdin
f = File.new(ARGV[1], 'r') unless ARGV.size &amp;#x3C; 2

table_name = ''
to_binary = []
to_text = []

while not f.eof? do
  line = f.readline

  # Read table name and clear sql statements
  if /^CREATE TABLE.*`([a-z_]*)`.*$/i =~ line then
    table_name = $1
    to_binary = []
    to_text = []
  end

  # prepare conversion statements for char, varchar and text
  if /^ *`([a-z_]*)` (char|varchar|text)([^,]*),?$/i =~ line then
    case $2
    when 'char' then newcol = 'binary'
    when 'varchar' then newcol = 'varbinary'
    when 'text' then newcol = 'blob'
    end

    # don't convert columns with explicit character set
    type = $3.downcase
    next if type.include? &quot;character&quot; or type.include? &quot;collate&quot;

    to_binary &amp;#x3C;&amp;#x3C; &quot;ALTER TABLE `#{table_name}` MODIFY `#{$1}` #{newcol}#{$3};&quot;
    to_text &amp;#x3C;&amp;#x3C; &quot;ALTER TABLE `#{table_name}` MODIFY `#{$1}` #{$2}#{$3};&quot;
  end

  # At the end of table definition puts sql statements
  if /^\) ENGINE=.*$/ =~ line then
    to_binary.each { |s| puts s }
    puts &quot;ALTER TABLE `#{table_name}` CHARACTER SET #{targetEnc};&quot;
    to_text.each { |s| puts s }
  end
end&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;&lt;p&gt;This worked for me perfectly, but be careful – you’re modifying your original data.&lt;/p&gt;
</description>
        <pubDate>Mon, 27 Dec 2010 00:00:00 GMT</pubDate>
        <link>https://adamwrobel.com/blog/2010/12/27/converting-or-fixing-mysql-table-character-set/</link>
        <guid isPermaLink="true">https://adamwrobel.com/blog/2010/12/27/converting-or-fixing-mysql-table-character-set/</guid>
        <category>mysql</category>
      </item>
      <item>
        <title>Trigger AdWords conversion on JavaScript event</title>
        <description>&lt;p&gt;When creating &lt;a href=&quot;http://choicevoice.ca&quot; target=&quot;_self&quot; rel=&quot;&quot;&gt;ChoiceVoice&lt;/a&gt; we wanted to greatly simplify the order
process. Wojtek decided to fit it all on single page powered by Ajax. This worked out
great, but at the end of the implementation we faced a minor problem. Google’s Adwords
don’t support programmatic conversion tracking. With the snippet provided by Google the
user triggers conversion by navigating to a site - like a “Thank you for your order” page.
This wasn’t good for us, because our clients are taken to PayPal immediately after filling
out the form.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;p&gt;The snippet that Google provides is really simple. Most of it is JavaScript itself, so why
not execute it from our own code? Let’s take a look:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;#x3C;script type=&quot;text/javascript&quot;&gt;
/* &amp;#x3C;![CDATA[ */
var google_conversion_id = 1234567890;
var google_conversion_language = &quot;en&quot;;
var google_conversion_format = &quot;3&quot;;
var google_conversion_color = &quot;ffffff&quot;;
var google_conversion_label = &quot;ABCDEFGHIJKlmnop-qr&quot;;
var google_conversion_value = 0;
/* ]]&gt; */
&amp;#x3C;/script&gt;
&amp;#x3C;script type=&quot;text/javascript&quot; src=&quot;http://www.googleadservices.com/pagead/conversion.js&quot;&gt;
&amp;#x3C;/script&gt;
&amp;#x3C;noscript&gt;
&amp;#x3C;div style=&quot;display:inline;&quot;&gt;
&amp;#x3C;img height=&quot;1&quot; width=&quot;1&quot; style=&quot;border-style:none;&quot; alt=&quot;&quot; src=&quot;http://www.googleadservices.com/pagead/conversion/1234567890/?label=ABCDEFGHIJKlmnop-qr&amp;#x26;amp;guid=ON&amp;#x26;amp;script=0&quot;/&gt;
&amp;#x3C;/div&gt;
&amp;#x3C;/noscript&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;&lt;p&gt;One way of triggering the conversion would be to insert the image that Google falls back
to in the &lt;code&gt;&amp;lt;noscript&amp;gt;&lt;/code&gt; tag. This would work, but I assume that this fallback method is
somehow inferior to the functionality offered by the included &lt;code&gt;conversion.js&lt;/code&gt; script (I’ve
noticed that it is requesting some additional resources).&lt;/p&gt;
&lt;p&gt;The other method would be to add something like this to your JavaScript files:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var google_conversion_id = 1234567890;
var google_conversion_language = &quot;en&quot;;
var google_conversion_format = &quot;3&quot;;
var google_conversion_color = &quot;ffffff&quot;;
var google_conversion_label = &quot;&quot;;
var google_conversion_value = 0;

var conversionLabels = {
  'voice-order': &quot;ABCDEFGHIJKlmnop-12&quot;,
  'copy-order': &quot;ABCDEFGHIJKlmnop-23&quot;
};


function trackConversion(label) {
  google_conversion_label = conversionLabels[label];
  $.getScript('https://www.googleadservices.com/pagead/conversion.js');
};

/* then somewhere in your UI code: */
trackConversion('voice-order');&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;&lt;p&gt;This code assumes that you’re using jQuery or something that provides the &lt;code&gt;$.getScript()&lt;/code&gt;
function. And also… it does &lt;em&gt;not&lt;/em&gt; work. If you use this code to execute the conversion
on user interaction, your page will end up blank. The user will be left with a white
screen.  Obviously not what we want him to see after placing an order with us.&lt;/p&gt;
&lt;p&gt;After some digging around I found out that the problem was Google’s &lt;code&gt;conversion.js&lt;/code&gt;
calling &lt;code&gt;document.write()&lt;/code&gt;. This function usually appends text to the document’s body, but
there’s a catch. If the document is fully loaded it won’t append, but instead it will
start a new document replacing the one currently displayed. There’s a reason for that&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;you probably don’t want to append anything after the &lt;code&gt;&amp;lt;/html&amp;gt;&lt;/code&gt; tag.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;But Google’s &lt;code&gt;conversion.js&lt;/code&gt; assumes that it is included inside the document’s body and
while the document is still being loaded. A solution is to overwrite the default
&lt;code&gt;document.write()&lt;/code&gt; method. A fairly simple task and surprisingly safe.&lt;/p&gt;
&lt;p&gt;In the end our &lt;code&gt;trackConversion()&lt;/code&gt; function should look like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function trackConversion(label) {
  google_conversion_label = conversionLabels[label];

  document.write = function(text) {
    $('#content').append(text);
  };
  $.getScript('https://www.googleadservices.com/pagead/conversion.js');
};&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;&lt;p&gt;The code allows you to have different conversions and select which one you want to
trigger. With little effort you can add a second argument to &lt;code&gt;trackConversion&lt;/code&gt; that will
assign conversion value.&lt;/p&gt;
</description>
        <pubDate>Thu, 23 Dec 2010 00:00:00 GMT</pubDate>
        <link>https://adamwrobel.com/blog/2010/12/23/trigger-adwords-conversion-on-javascript-event/</link>
        <guid isPermaLink="true">https://adamwrobel.com/blog/2010/12/23/trigger-adwords-conversion-on-javascript-event/</guid>
        <category>javascript</category>
        <category>flux inc</category>
      </item>
      <item>
        <title>Soft hyphen and in-page search in different browsers</title>
        <description>&lt;p&gt;When creating my main page I wanted to hyphenate words in some places. This can be
especially useful when putting content in narrow, justified columns. Unfortunately this
rather rudimentary technique in paper media is rarely seen on the web. Currently the best
way to break words on your web page is to literally[^1] add the soft-hyphen characters to
your text. Soft hyphen in html is encoded with a &lt;code&gt;&amp;amp;shy;&lt;/code&gt; entity.&lt;/p&gt;
&lt;p&gt;Fortunately, unlike how some posts dated a few years back describe it, this entity now
displays properly in all modern browsers. Properly means that &lt;code&gt;&amp;amp;shy;&lt;/code&gt; displays a hyphen
when there is a need to break a word, but doesn’t display anything when the word fits the
line. There are other issues though.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;pre&gt;&lt;code&gt;&amp;#x3C;div style=&quot;border: 1px solid #000; width: 15em; display: inline-block;&quot;&gt;
an&amp;#x26;shy;tidis&amp;#x26;shy;es&amp;#x26;shy;tab&amp;#x26;shy;lish&amp;#x26;shy;ment
&amp;#x3C;/div&gt;
&amp;#x3C;div style=&quot;border: 1px solid #000; width: 3em; display: inline-block;&quot;&gt;
an&amp;#x26;shy;tidis&amp;#x26;shy;es&amp;#x26;shy;tab&amp;#x26;shy;lish&amp;#x26;shy;ment
&amp;#x3C;/div&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;&lt;div class=&quot;vertical-rhythm&quot;&gt;
&lt;div style=&quot;border: 1px solid #000; width: 3em; line-height: 100%; display: inline-block;&quot;&gt;
an&amp;shy;tidis&amp;shy;es&amp;shy;tab&amp;shy;lish&amp;shy;ment
&lt;/div&gt;
&lt;div style=&quot;border: 1px solid #000; width: 15em; line-height: 100%; display: inline-block;&quot;&gt;
an&amp;shy;tidis&amp;shy;es&amp;shy;tab&amp;shy;lish&amp;shy;ment
&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;It’s not perfect though. Beside some text selection and copying quirks that you might
notice there’s also a major problem. Some browsers do not handle in-page search correctly.
Try searching for “antidisestablishment” on this page.&lt;/p&gt;
&lt;p&gt;Two browsers that I’ve tested seem to handle this correctly. All the other not only do not
find a word that had hyphen inserted, but don’t even find a word that fits the line if
it contains some &lt;code&gt;&amp;amp;shy;&lt;/code&gt; entities inside it. I’m going to lay it out in a table
including both possible behaviors even though there’s currently no browser that
demonstrates partial support for searching for words with soft hyphens.&lt;/p&gt;
&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;&lt;/th&gt;
      &lt;th style=&quot;padding: 0 1em 0 1em&quot;&gt;Finds a word that fits&lt;/th&gt;
      &lt;th style=&quot;padding: 0 1em 0 1em&quot;&gt;Finds a hyphenated word&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Chrome 8&lt;/td&gt;
      &lt;td class=&quot;center&quot; style=&quot;color: green&quot;&gt;&amp;#10003;&lt;/td&gt;
      &lt;td class=&quot;center&quot; style=&quot;color: green&quot;&gt;&amp;#10003;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Firefox 3.6&lt;/td&gt;
      &lt;td class=&quot;center&quot; style=&quot;color: green&quot;&gt;&amp;#10003;&lt;/td&gt;
      &lt;td class=&quot;center&quot; style=&quot;color: green&quot;&gt;&amp;#10003;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Safari 5&lt;/td&gt;
      &lt;td class=&quot;center&quot; style=&quot;color: red&quot;&gt;&amp;#10007;&lt;/td&gt;
      &lt;td class=&quot;center&quot; style=&quot;color: red&quot;&gt;&amp;#10007;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Opera 11&lt;/td&gt;
      &lt;td class=&quot;center&quot; style=&quot;color: red&quot;&gt;&amp;#10007;&lt;/td&gt;
      &lt;td class=&quot;center&quot; style=&quot;color: red&quot;&gt;&amp;#10007;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;IE 8&lt;/td&gt;
      &lt;td class=&quot;center&quot; style=&quot;color: red&quot;&gt;&amp;#10007;&lt;/td&gt;
      &lt;td class=&quot;center&quot; style=&quot;color: red&quot;&gt;&amp;#10007;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;You might also be interested how search engines handle this.
&lt;a href=&quot;http://translate.google.com/translate?js=n&amp;amp;prev=_t&amp;amp;hl=en&amp;amp;ie=UTF-8&amp;amp;layout=2&amp;amp;eotf=1&amp;amp;sl=de&amp;amp;tl=en&amp;amp;u=http%3A%2F%2Fwww.gurkcity.de%2Fblog%2FGoogle-und-die-shy-Entity-55.html&quot; target=&quot;_self&quot; rel=&quot;&quot;&gt;This post&lt;/a&gt;
suggests that at least google doesn’t have any problem with the &lt;code&gt;&amp;amp;shy;&lt;/code&gt; entity.&lt;/p&gt;
&lt;p&gt;[^1]: Literally doesn’t mean you have to type them in manually. I use patched Text::Hyphen Ruby gem and a Rails block helper to calculate and insert the hyphens for me.&lt;/p&gt;
</description>
        <pubDate>Mon, 20 Dec 2010 00:00:00 GMT</pubDate>
        <link>https://adamwrobel.com/blog/2010/12/20/soft-hyphen-and-in-page-search-in-different-browsers/</link>
        <guid isPermaLink="true">https://adamwrobel.com/blog/2010/12/20/soft-hyphen-and-in-page-search-in-different-browsers/</guid>
        <category>web standards</category>
      </item>
  </channel>
</rss>
