Class: Browser::LocalStorage

Inherits:
Object
  • Object
show all
Defined in:
lib/opal/jquery/local_storage.rb

Overview

LocalStorage is a simple wrapper around localStorage in the browser.

Instead of using the class directly, the main instance LocalStorage should be used instead. This class can be used to wrap an instance from another window or iframe if required.

Usage

LocalStorage is not included by default when you require opal-jquery, so you will need to require it explicitly in your code:

require 'opal/jquery'
require 'opal/jquery/local_storage'

puts LocalStorage
# => #<LocalStorage>

Example Usage

LocalStorage['foo'] = 'hello world'

LocalStorage['foo'] # => "hello world"
LocalStorage['bar'] # => nil

See Also:

Instance Method Summary collapse

Constructor Details

#initialize(storage) ⇒ LocalStorage


30
31
32
# File 'lib/opal/jquery/local_storage.rb', line 30

def initialize(storage)
  @storage = storage
end

Instance Method Details

#[](key) ⇒ String?

Retrieve an object from Browser::LocalStorage.

Only string values can be stored, so any object will be returned as a string. You will need to handle any conversion back into a normal object. JSON.parse could be used, for example, to parse back into arrays or hashes.

If a key is not present in the storage, then nil will be returned.


62
63
64
65
66
67
# File 'lib/opal/jquery/local_storage.rb', line 62

def [](key)
  %x{
    var value = #@storage.getItem(key);
    return value == null ? nil : value;
  }
end

#[]=(key, value) ⇒ Object

Set a value in storage.

Values stored in Browser::LocalStorage will be stored as strings. To store any other type of object, you will need to convert them to a string first, and then convert them back from #[]. For this reason it is recommended to only store JSON based objects in storage, so they can be easily converted back and forth.


44
45
46
47
48
49
# File 'lib/opal/jquery/local_storage.rb', line 44

def []=(key, value)
  %x{
    #@storage.setItem(key, value);
    return value;
  }
end

#clearObject

Remove all key/values from storage


78
79
80
# File 'lib/opal/jquery/local_storage.rb', line 78

def clear
  `#@storage.clear()`
end

#delete(key) ⇒ Object

Removes a specific key from storage. If the key does not exist then there is no side effect.


73
74
75
# File 'lib/opal/jquery/local_storage.rb', line 73

def delete(key)
  `#@storage.removeItem(key)`
end