active_element

0.0.13
Light Mode Dark Mode

JSON

The json component provides a mechanism for converting Ruby objects and storing them as JSON within your HTML so that it can be later accessed by any Javascript code running in your application.

The implementation is simple but is intended to avoid repetition of serialization and ensures that all JSON data you output is stored consistently in one location.

JSON data is available to Javascript code as ActiveElement.jsonData. The component receives a key and an object to be serialized. The key is converted to camel case to provide conventionally-named Javascript accessors.

Note that only the data key is converted to camel case. The data object itself is not transformed in any way aside from converting directly to JSON.

subject do
  active_element.component.json :my_data, { some: { example: 'data' } }
end

it { is_expected.to include '"myData"' }
<script type="text/javascript">
  window.ActiveElement = window.ActiveElement || {};
  ActiveElement.jsonData = ActiveElement.jsonData || {};

  ActiveElement.jsonData = {
    ...ActiveElement.jsonData,
    ...{"myData":{"some":{"example":"data"}}}
  };
</script>

The data is now available to Javascript code - try running the following code in your browser’s Javascript console:

console.log(ActiveElement.jsonData.myData);

Documentation generated by rspec-documentation