Skip to content

Commit

Permalink
Edit AS core extension docs [ci skip]
Browse files Browse the repository at this point in the history
Add String#truncate_bytes and Hash#deep_transform_values/!. Clarify Enumerable#index_with.
  • Loading branch information
Sean0628 authored and georgeclaghorn committed Oct 27, 2019
1 parent d2e8b83 commit 4f9f9ca
Showing 1 changed file with 39 additions and 2 deletions.
41 changes: 39 additions & 2 deletions guides/source/active_support_core_extensions.md
Expand Up @@ -1151,6 +1151,24 @@ In above examples "dear" gets cut first, but then `:separator` prevents it.

NOTE: Defined in `active_support/core_ext/string/filters.rb`.

### `truncate_bytes`

The method `truncate_bytes` returns a copy of its receiver truncated to at most `bytesize` bytes:

```ruby
"πŸ‘πŸ‘πŸ‘πŸ‘".truncate_bytes(15)
# => "πŸ‘πŸ‘πŸ‘β€¦"
```

Ellipsis can be customized with the `:omission` option:

```ruby
"πŸ‘πŸ‘πŸ‘πŸ‘".truncate_bytes(15, omission: "πŸ––")
# => "πŸ‘πŸ‘πŸ––"
```

NOTE: Defined in `active_support/core_ext/string/filters.rb`.

### `truncate_words`

The method `truncate_words` returns a copy of its receiver truncated after a given number of words:
Expand Down Expand Up @@ -2036,8 +2054,10 @@ The method `index_with` generates a hash with the elements of an enumerable as k
is either a passed default or returned in a block.

```ruby
%i( title body created_at ).index_with { |attr_name| post.public_send(attr_name) }
# => { title: "hey", body: "what's up?", … }
post = Post.new(title: "hey there", body: "what's up?")

%i( title body ).index_with { |attr_name| post.public_send(attr_name) }
# => { title: "hey there", body: "what's up?" }

WEEKDAYS.index_with(Interval.all_day)
# => { monday: [ 0, 1440 ], … }
Expand Down Expand Up @@ -2710,6 +2730,23 @@ Active Record does not accept unknown options when building associations, for ex

NOTE: Defined in `active_support/core_ext/hash/keys.rb`.

### Working with Values

#### `deep_transform_values` and `deep_transform_values!`

The method `deep_transform_values` returns a new hash with all values converted by the block operation. This includes the values from the root hash and from all nested hashes and arrays.

```ruby
hash = { person: { name: 'Rob', age: '28' } }

hash.deep_transform_values{ |value| value.to_s.upcase }
# => {person: {name: "ROB", age: "28"}}
```

There's also the bang variant `deep_transform_values!` that destructively converts all values by using the block operation.

NOTE: Defined in `active_support/core_ext/hash/deep_transform_values.rb`.

### Slicing

The method `slice!` replaces the hash with only the given keys and returns a hash containing the removed key/value pairs.
Expand Down

0 comments on commit 4f9f9ca

Please sign in to comment.