Class: Browser::LocalStorage
- Inherits:
-
Object
- Object
- Browser::LocalStorage
- 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
Instance Method Summary collapse
-
#[](key) ⇒ String?
Retrieve an object from LocalStorage.
-
#[]=(key, value) ⇒ Object
Set a value in storage.
-
#clear ⇒ Object
Remove all key/values from storage.
-
#delete(key) ⇒ Object
Removes a specific
key
from storage. -
#initialize(storage) ⇒ LocalStorage
constructor
A new instance of LocalStorage.
Constructor Details
#initialize(storage) ⇒ LocalStorage
Returns a new instance of LocalStorage.
32 33 34 |
# File 'lib/opal/jquery/local_storage.rb', line 32 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.
64 65 66 67 68 69 |
# File 'lib/opal/jquery/local_storage.rb', line 64 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.
46 47 48 49 50 51 |
# File 'lib/opal/jquery/local_storage.rb', line 46 def []=(key, value) %x{ #@storage.setItem(key, value); return value; } end |
#clear ⇒ Object
Remove all key/values from storage
80 81 82 |
# File 'lib/opal/jquery/local_storage.rb', line 80 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.
75 76 77 |
# File 'lib/opal/jquery/local_storage.rb', line 75 def delete(key) `#@storage.removeItem(key)` end |